[英]Get constructor/instance from generic type in TypeScript
I am trying to create instance from generic type T
for example, 我试图从泛型类型
T
创建实例,例如,
class Factory {
public static generate<T>(): T {
return new T();
}
}
But since T
is just a type not constructor , we can't do that. 但由于
T
只是一种类型而不是构造函数 ,我们不能这样做。
Is it impossible to create an instance from a generic type in TypeScript? 是否无法在TypeScript中从泛型类型创建实例?
I'v also read these articles but could not found a solution. 我也读过这些文章,但找不到解决方案。
The type information used in TypeScript is erased before runtime, so the information about T
is not available when you make the call to new T()
. TypeScript中使用的类型信息在运行时之前被删除,因此当您调用
new T()
时,有关T
的信息不可用。
That's why all of the alternate solutions depend upon the constructor being passed, such as with this example of creating a class dynamically : 这就是为什么所有替代解决方案都依赖于传递的构造函数,例如动态创建类的示例 :
interface ParameterlessConstructor<T> {
new (): T;
}
class ExampleOne {
hi() {
alert('Hi');
}
}
class Creator<T> {
constructor(private ctor: ParameterlessConstructor<T>) {
}
getNew() {
return new this.ctor();
}
}
var creator = new Creator(ExampleOne);
var example = creator.getNew();
example.hi();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.