假设我有一个类:
public class A {
foo: string;
}
如何定义一个函数,以便它接受类的类型并返回它的实例?像这样:
function bar<T>(c: typeof T): T {
return new c();
}
const a: A = bar(A);
TypeScript 文档实际上有一个在泛型中使用类类型的示例:
使用泛型在 TypeScript 中创建工厂时,有必要通过构造函数引用类类型。例如
function create<T>(c: {new(): T; }): T { return new c(); }
new()
是一个构造函数
要完成丹尼尔的回答:
我们可以使用type Constructor<T = {}> = new (...args: any[]) => T;
更明确地指示构造函数的参数(但没有静态类型检查(。
type Constructor<T = {}> = new (...args: any[]) => T;
function create<T>(Klass: Constructor<T>, ...args: any[]): T {
return new Klass(...args);
}
class A0 { }
class A1 { constructor(readonly arg: string) {} }
const a0 = create(A0);
console.log(a0 instanceof A0); // true
const a1 = create(A1, 'arg');
console.log(a1 instanceof A1, a1.arg === 'arg'); // true, true
结果→在 TS 操场上运行它。