我需要从类中提取类型,可以通过以下代码演示:
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
部分,TOKP
为Test
,这是正确的。
在With Constructor()
部分,TNOP
为any
,输入错误。
我的问题是:如果我必须使用typeof Test & Constructor<Test>
,我该如何阻止TNOP
的类型为any
?我希望它是Test
。
答案 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']
添加更多类型安全性),但希望其中一个可以帮助您。祝你好运!