TypeScript转发参数时如何保留泛型类型信息
问题根因
你遇到的泛型推导丢失问题,来自TypeScript对泛型类构造函数的类型处理规则:
- 对带泛型的类直接执行
typeof获取构造函数类型时,如果没有显式补全构造函数的泛型透传签名,TS会默认将类的未指定泛型参数替换为其上界(无显式约束的泛型上界就是unknown) - 基于这个已经退化的构造函数提取
ConstructorParameters时,拿到的参数类型已经完全切断了原泛型的动态推导链路,最终无论传入什么类型的实参,返回值都会被推导为Example<unknown>。
可保留泛型信息的实现方案
直接给工厂函数补全可推导的泛型
这是最简洁、兼容性最好的实现,不需要依赖构造函数元数据反向提取参数,直接让TS从实参自动推导泛型:
class Example<T> { constructor(public value: T) {} } // 给包装函数独立声明可推导的泛型T function newExample<T>(value: T) { return new Example(value); } // 类型推导完全符合预期 const exampleNumber = newExample(3); // 推导为 Example<number> const exampleString = newExample('foo'); // 推导为 Example<string>
基于原构造函数元数据实现透传
如果业务场景要求必须复用类的构造参数、不想手写参数列表,就需要先把原本退化的typeof Example构造函数类型,修复成可以透传泛型的签名:
class Example<T> { constructor(public value: T) {} } // 定义和类构造函数匹配的、支持泛型透传的构造签名 type GenericExampleConstructor = new <T>(value: T) => Example<T>; // 将原构造函数断言为支持泛型透传的类型 const GenericExample = Example as GenericExampleConstructor; // 基于修复后的构造函数提取参数,完整保留泛型推导链路 function newExample(...args: ConstructorParameters<typeof GenericExample>) { return new GenericExample(...args); } // 类型推导符合预期 const exampleNumber = newExample(3); // Example<number> const exampleString = newExample('foo'); // Example<string>
注意:第二种写法依赖TS 4.7及以上版本的泛型构造函数推导能力,低版本TS中可能无法正确完成参数类型提取。
内容的提问来源于stack exchange,提问作者Kiwi
相关产品推荐
相关产品推荐

