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

如何在TypeScript中实现带类型提示的双函数合并?

为函数合并器添加TypeScript类型提示

我们的目标是通过参数组合将两个函数合并为一个,这个操作在JavaScript中很容易实现,但在TypeScript中要保留完整的类型提示需要借助泛型工具类型来处理。

你给出的Proxy实现逻辑是可行的,但原代码中combiner函数使用了Function类型,完全丢失了输入函数的参数和返回值类型信息,所以无法生成类型提示。我们可以通过泛型来修复这个问题:

带类型提示的combiner实现

// 定义合并后函数的类型:参数是两个函数参数的拼接,返回值是两者返回值的元组
type CombinedFunction<F1 extends (...args: any[]) => any, F2 extends (...args: any[]) => any> = 
  (...args: [...Parameters<F1>, ...Parameters<F2>]) => [ReturnType<F1>, ReturnType<F2>]

const combiner = <F1 extends (...args: any[]) => any, F2 extends (...args: any[]) => any>(
  f1: F1, 
  f2: F2
): CombinedFunction<F1, F2> => {
  return new Proxy(f1 as any, {
    apply(target, thisArg, args) {
      // 用slice替代splice,避免修改原参数数组
      const f1Args = args.slice(0, f1.length);
      const f2Args = args.slice(f1.length);
      
      const result1 = f1.apply(thisArg, f1Args);
      const result2 = f2.apply(thisArg, f2Args);
      
      // 返回两个函数的执行结果组成的元组
      return [result1, result2];
    }
  }) as CombinedFunction<F1, F2>;
};

测试示例

const f1 = (a: number) => {
  return (a + 1) * 2;
} 

const f2 = (b: string, c: string[]) => {
  c.push(b);
  return c;
}

const f = combiner(f1, f2);
// 此时f会被推导为类型:(a: number, b: string, c: string[]) => [number, string[]]

// 调用时会有完整的参数类型提示,返回值也能正确解构
const [res1, res2] = f(1, 'foo', ['bar']);
// res1: number,res2: string[]

关键说明

  1. 泛型工具类型:使用Parameters<F>提取函数的参数类型数组,ReturnType<F>提取函数的返回值类型,通过展开语法[...Parameters<F1>, ...Parameters<F2>]合并两个函数的参数列表。
  2. Proxy类型断言:由于TypeScript对Proxy的类型推导支持有限,需要用as any和as CombinedFunction<F1, F2>来强制指定类型,这是处理Proxy时的常见操作。
  3. 参数处理优化:原代码中的splice会修改原args数组,换成slice可以避免意外的副作用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 12:25:40