工厂函数创建类的实例:
class A {
name: string
}
function factory<T>(Cl): T {
return new Cl()
}
let a = factory<A>(A)
a.name // OK
我想避免重复 A
在:factory<A>(A)
.泛型实例类型应该能够从类类型中推断出来,不是吗?
我试过这段代码:
function factory<T>(Cl: typeof T): T { // Error: Cannot find name 'T'
return new Cl()
}
有办法吗?
最佳答案
基于 typescript documentation :
When creating factories in TypeScript using generics, it is necessary to refer to class types by their constructor functions.
所以你必须做这样的事情:
function factory<T>(Cl: { new(): T; }): T {
return new Cl();
}
在上面的代码中,Cl
必须是一个至少有一个返回 T
泛型的构造函数的类型。
所以类型推断会起作用:
let a = factory(A);
a.name;
你不需要指定 A
的类型,因为编译器知道它。
关于class - TypeScript 中的泛型 : How to infer the type of an instance from the class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40319162/