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

如何根据类构造函数传入的函数参数为类方法参数添加类型

TypeScript类方法参数类型随构造函数传入函数动态约束的实现

要实现根据构造函数传入的函数参数类型,自动约束类中method方法的参数类型,核心是利用TypeScript泛型捕获传入函数的参数类型信息,具体实现如下:

修改后的类代码

export class Test<Args extends any[]> {
    private func: (...args: Args) => void;
    
    constructor(func: (...args: Args) => void) {
        this.func = func;
    }
    
    method(...args: Args) {
        return this.func(...args);
    }
}

使用示例

const testFunction = (a: number, b: string) => {}

const test = new Test(testFunction); // 无TypeScript警告,泛型自动推导参数类型为[number, string]

test.method(1, 'e'); // 参数符合要求,无警告
test.method('1', 2); // 触发TypeScript警告,参数类型不匹配testFunction的要求

原理说明

  • 泛型Args extends any[]用于捕获构造函数传入函数的参数类型数组,实例化Test时,TypeScript会自动根据传入的testFunction推导Args的具体类型(此处为[number, string])。
  • 类中的func属性和method方法都使用该泛型类型约束参数,确保method的参数类型与传入的函数完全一致。
  • 构造函数接收的参数类型与泛型绑定,因此传入匹配函数时不会出现错误提示。

内容的提问来源于stack exchange,提问作者Алексей Смирнов

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 14:12:33