TypeScript 中的泛型:如何从 class 推断实例的类型
Generics in TypeScript: How to infer the type of an instance from the class
工厂函数创建 classes:
的实例
class A {
name: string
}
function factory<T>(Cl): T {
return new Cl()
}
let a = factory<A>(A)
a.name // OK
我想避免在 factory<A>(A)
中重复 A
。泛型实例类型应该能够从 class 类型推断出来,不应该吗?
我试过这段代码:
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
必须是一个至少具有 return T
泛型构造函数的类型。
所以类型推断会起作用:
let a = factory(A);
a.name;
您不需要指定 A
的类型,因为编译器知道它。
工厂函数创建 classes:
的实例class A {
name: string
}
function factory<T>(Cl): T {
return new Cl()
}
let a = factory<A>(A)
a.name // OK
我想避免在 factory<A>(A)
中重复 A
。泛型实例类型应该能够从 class 类型推断出来,不应该吗?
我试过这段代码:
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
必须是一个至少具有 return T
泛型构造函数的类型。
所以类型推断会起作用:
let a = factory(A);
a.name;
您不需要指定 A
的类型,因为编译器知道它。