You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否重载TypeScript泛型类型?优化torgle函数泛型参数

可以通过函数重载实现,无需拆分函数

完全不用拆成两个函数,用TypeScript的函数重载就能同时支持两种用法:

实现代码

// 重载1:支持自动推导/手动指定A、B,参数符合模板字符串格式
function torgle<A extends string, B extends number>(flurg: `[${A}]<>[${B}]`): string;
// 重载2:支持自定义任意字符串类型的Flurg,无需额外泛型参数
function torgle<Flurg extends string>(flurg: Flurg): string;

// 函数实现体(兼容两种重载逻辑)
function torgle<Flurg extends string>(flurg: Flurg): string {
    return `hello, ${String(flurg).replace(/[[\]<>]/g, '')}`;
}

测试两种用法

  1. 标准模板字符串场景(自动推导或手动指定A、B都可以):
// 自动推导A='blue',B=32
torgle('[blue]<>[32]'); 
// 输出:hello, blue32

// 手动指定泛型参数
torgle<'blue', 32>('[blue]<>[32]');
// 同样输出:hello, blue32
  1. 自定义Flurg场景(无需指定无用的A、B参数):
torgle('cheeseburger');
// 输出:hello, cheeseburger

// 也可以显式指定泛型(可选)
torgle<'cheeseburger'>('cheeseburger');

原理说明

  • 当传入符合[${A}]<>[${B}]格式的参数时,TS会匹配第一个重载签名,自动推导或使用你指定的A、B泛型;
  • 当传入任意其他字符串时,TS会匹配第二个重载签名,直接使用你传入的字符串作为Flurg类型,不需要额外的泛型参数;
  • 实现体的泛型Flurg extends string是最宽泛的约束,能兼容两种重载的参数类型,保证逻辑统一。

内容的提问来源于stack exchange,提问作者Sasgorilla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 21:30:15