class - TypeScript 中的泛型 : How to infer the type of an instance from the class

标签 class generics typescript instance typeof

工厂函数创建类的实例:

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/

相关文章:

java - 使用通用 Map 参数重写方法

c# - 大量代码重复的问题

reactjs - 部署错误 : Argument of type 'MiniCssExtractPlugin' is not assignable to parameter of type 'Plugin'

python - Python 中的实例变量?不断出现分配错误

C++ "Count the number of collisions at each slot in the hash table"

c# - 将项目添加到列表 T 通用方法

typescript - 如何通过指定每个属性及其值来实例化 TypeScript 中的对象?

javascript - Typescript 中的模块系统

c++ - 这种C++类声明是什么意思?

c# - 关于类的属性更改时如何使 UI 使用react的任何想法?