【问题标题】:Factory in typescript with a generic argument带有通用参数的打字稿工厂
【发布时间】:2020-09-25 08:38:41
【问题描述】:

我正在尝试在 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 以上代码。

【问题讨论】:

    标签: typescript generics factory


    【解决方案1】:

    您的问题是您将泛型设置在错误的位置。在make(value) 中,value 应该是没有任何 TypeScript 定义的可运行代码。所以调用 make(G&lt;number&gt;) 是错误的,因为你不能调用 TypeScript 泛型作为参数。

    定义泛型,需要写在括号前:

    make<G<number>>(G)
    

    所以在这里,G&lt;number&gt; 是您提供的类型,G 是“有效”可运行代码。

    看看playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-06
      • 1970-01-01
      • 2020-08-10
      • 2020-01-03
      • 1970-01-01
      • 1970-01-01
      • 2017-01-18
      • 1970-01-01
      相关资源
      最近更新 更多