得到`(Typeof TheClass)[' prototype']`和`&`式交集

时间:2018-05-01 12:00:02

标签: typescript

我需要从类中提取类型,可以通过以下代码演示:

abstract class Test {}

/**
 * Basic
 */
type TOK = typeof Test
type TOKP = TOK['prototype']
// TOKP = Test

/**
 * With Constructor()
 */
type Constructor<T> = new(...args: any[]) => T
type TNO = typeof Test & Constructor<Test>
type TNOP = TNO['prototype']
// TNOP = any
// Question: how to make TNOP as the type `Test` instead of `any`?

Basic部分,TOKPTest,这是正确的。 在With Constructor()部分,TNOPany,输入错误。

我的问题是:如果我必须使用typeof Test & Constructor<Test>,我该如何阻止TNOP的类型为any?我希望它是Test

1 个答案:

答案 0 :(得分:2)

您的问题是构造函数被视为Function,其接口在标准库lib.es5.d.ts中定义为具有prototype: any属性。

有多种方法可以做你想要的。一种是将Constructor<T>定义修改为:

type Constructor<T> = { new(...args: any[]): T, prototype: T };
type TNOP = TNO['prototype']; // Test

如果你不能这样做而且你使用的是TypeScript v2.8或更高版本,你可以使用conditional types(具体来说,type inference in conditional types)来提取构造函数的实例类型,无论是否prototype按您期望的方式设置:

type InstanceType<T extends new(...args: any[]) => any> = 
  T extends new (...args: any[]) => infer U ? U : never

type TNOP = InstanceType<TNO>; // Test

可能还有其他解决方案(例如,修改lib.es5.d.ts的本地副本以向Function['prototype']添加更多类型安全性),但希望其中一个可以帮助您。祝你好运!