我正在尝试在返回通用类型的Typescript中实现工厂。
已经弄清楚了我需要将类型作为第一个参数传递,并将其类型设置为CTOR签名(new () => T
在此示例中)。
当我想将通用类型传递给工厂时,问题就开始了-我收到一条错误消息:Value of type 'typeof G' is not callable. Did you mean to include 'new'?(2348)
。
有什么办法可以做到这一点?
这是问题的简化版本:
// Generic class
class G<T>{}
// Standard non generic
class B{}
function make<T>(t: new () => T){
return new t()
}
// Works
make(B)
// Value of type 'typeof G' is not callable. Did you mean to include 'new'?(2348)
make(G<number>)
打字稿操场链接到上面的代码。
您的问题是将通用名称设置在错误的位置。在中make(value)
,value
应该是没有任何TypeScript定义的可运行代码。因此调用make(G<number>)
是错误的,因为您不能调用TypeScript泛型作为参数。
要定义泛型,您需要在括号之前编写它:
make<G<number>>(G)
因此,这里G<number>
是您提供的类型,并且G
是“有效”的可运行代码。
看看操场。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句