TypeScript中NewableFunction接口的用途及设计疑问
TypeScript冷门内置类型:
VoidFunction与NewableFunction的困惑 TypeScript内置了一个鲜为人知的接口VoidFunction,它明确代表无参数、返回值为void的函数,行为完全符合预期:
// 结果符合预期 type VoidParams1 = Parameters<VoidFunction>; // ^? []
VoidFunction不具备构造能力,因此使用ConstructorParameters会直接报错,这也在情理之中。
但另一个更冷门的内置类型NewableFunction就充满迷惑性了——从命名来看,它似乎应该代表可通过new调用的构造函数(对应new (...args) => ...这类构造签名),但实际使用时却处处是意外:
1. 不兼容工具类型
NewableFunction既不满足Parameters工具类型的约束(因为它不是普通函数),也不满足ConstructorParameters的约束:
//@ts-expect-error 是构造函数而非普通函数 type CtorParams1 = Parameters<NewableFunction>; // 无法理解的错误 type CtorParams2 = ConstructorParameters<NewableFunction>; // 错误提示: ^^^^^^^^^^^^^^^ // Type 'NewableFunction' does not satisfy the constraint 'abstract new (...args: any) => any'.
2. 类型注解的诡异行为
将NewableFunction作为函数参数类型时,会出现不符合直觉的兼容性问题:
function newfn(f: NewableFunction) {} // 这行代码正常通过检查 newfn(class {}); // 但下面这行报错,可`new Date()`明明是合法的构造调用 newfn(Date); // ^^^^ // 错误提示:Argument of type 'DateConstructor' is not assignable to parameter of type 'NewableFunction'. // Types of property 'apply' are incompatible. // ... // Type 'new () => any' is not assignable to type '(this: any) => any'.
更奇怪的是,它似乎只接受严格只能通过new调用的函数:传入Date会报错,但传入Float32Array却能正常通过检查。
核心疑问
- 既然
NewableFunction无法被当作正常的构造函数类型使用,它的存在意义到底是什么? - 为什么TypeScript不直接内置
new (...args: any[]) => any这种更通用、符合直觉的构造函数类型?
官方相关议题ms/TS#44337并未给出明确答案。
内容的提问来源于stack exchange,提问作者k-tten
相关产品推荐
相关产品推荐

