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

TypeScript中如何基于回调参数为接收回调的函数做类型标注?

TypeScript泛型改造executeBlockingFunction函数

你可以通过泛型约束结合TypeScript内置的Parameters和ReturnType工具类型,实现严格的类型标注,替代any并保证类型一致性。以下是改造后的完整代码:

public static executeBlockingFunction<T extends (...args: any[]) => any>(
    callbackFunction: T,
    callbackArguments: Parameters<T>
): ReturnType<T> {
    // execute some code before calling the callback function
    
    const callbackReturn = callbackFunction.call(callbackFunction, ...callbackArguments);

    // executes some more code before returning the callback return
   
    return callbackReturn;
}

关键部分解释:

  • 泛型参数T:用T extends (...args: any[]) => any约束T必须是一个函数类型,TypeScript会自动推断传入回调的具体函数类型。
  • Parameters<T>:内置工具类型,提取T类型函数的所有参数组成元组类型,完美匹配callbackArguments的类型要求。
  • ReturnType<T>:内置工具类型,提取T类型函数的返回值类型,确保executeBlockingFunction的返回类型和回调函数完全一致。

使用示例:

// 定义一个具体的回调函数
const add = (a: number, b: number): number => a + b;

// 调用改造后的函数,TypeScript会自动推断参数和返回类型
const result = YourClass.executeBlockingFunction(add, [1, 2]);
// result的类型会被推断为number,和add的返回类型一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:55:27