网站搜索

typescript - 将 typeof 作为参数类型使用


假设我有一个类:

public class A {
  foo: string;
}

我如何定义一个函数,使它接受类的类型并返回该类的实例?像这样:

function bar<T>(c: typeof T): T {
  return new c();
}

const a: A = bar(A);

答案#1

TypeScript 文档实际上有一个关于在泛型中使用类类型的示例:

在使用泛型创建 TypeScript 工厂时,有必要通过它们的构造函数引用类类型。例如,

function create<T>(c: {new(): T; }): T {
    return new c();
}

new() 是一个构造函数

答案#2

为了补充丹尼尔的回答:

我们可以使用 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 playground 上运行它。