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

如何为模拟原函数接口的TypeScript高阶函数正确定义类型?

解决方案

要让高阶函数high保留原函数的参数类型(包括可选参数),需要通过泛型元组精准捕获原函数的参数结构,而非用any[]抹除类型信息。

修改后的代码

export function high<P extends any[], R>(fn: (...args: P) => R) {
  return (...args: P) => {
    const moddedArgs = args.map((el) =>
      typeof el === "string" ? el + "OMG" : el
    );

    // 类型断言确保处理后的参数与原函数参数类型兼容
    return fn(...(moddedArgs as P));
  };
}

const test1 = (nr1: number, str1?: string) => (str1 ?? "Wow").repeat(nr1);

const test2 = high(test1);

// 现在 test2 的类型与 test1 完全一致
type Test2 = typeof test2;
// type Test2 = (nr1: number, str1?: string) => string

关键说明

  1. 泛型参数捕获类型:
    • P extends any[]:精准捕获原函数的参数元组,包含可选参数、剩余参数等完整结构
    • R:捕获原函数的返回值类型
  2. 保留参数结构:返回函数的参数类型直接复用P,确保和原函数的参数个数、类型、可选性完全匹配
  3. 类型安全断言:moddedArgs as P是安全操作——我们仅对字符串类型做追加处理,其他类型保持原样,与原参数类型完全兼容

效果验证

现在调用test2时,TypeScript会提供和test1完全相同的类型提示:

  • 必须传入第一个number类型参数
  • 第二个string类型参数可选
  • 返回值类型仍为string

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:10:42