[英]Infer constructor type in TypeScript
Is it possible to infer the constructor type of a class in TypeScript? 是否可以在TypeScript中推断类的构造函数类型? I tried this but it seems not to work:
我尝试了这个,但似乎不起作用:
type Constructor<K> = K extends { new: infer T } ? T : any;
Instead of trying to infer it, can you refer to class types by their constructor functions like this? 可以尝试通过类的构造函数引用类类型,而不是尝试进行推断吗?
type Constructor<K> = { new(): K };
const x: Constructor<String> = String;
const s = new x();
There is already a predefined conditional type that allows you to extract the instance type from a class type, called InstanceType
已经有一个预定义的条件类型,它允许您从一个名为
InstanceType
的类类型中提取实例类型。
class A { private x: any}
type AInstance = InstanceType<typeof A> // same as A
The definition of this type is: 此类型的定义是:
type InstanceType<T extends new (...args: any) => any> = T extends new (...args: any) => infer R ? R : any;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.