带有通用参数的打字稿中的工厂

时间:2020-09-25 08:38:41

标签: typescript generics factory

我正在尝试在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>)

Typescript playground link到上面的代码。

1 个答案:

答案 0 :(得分:2)

您的问题是您将通用名称设置在错误的位置。在make(value)中,value应该是没有任何TypeScript定义的可运行代码。因此调用make(G<number>)是错误的,因为您不能调用TypeScript泛型作为参数。

要定义通用名称,您需要在括号之前编写它:

make<G<number>>(G)

因此,在这里,G<number>是您提供的类型,而G是“有效”可运行代码。

看看playground

相关问题