如何创建类数组?

Mak*_*toE 1 class typescript

我想在 TypeScript 中创建一个类数组。这在普通 JavaScript 中是可能的:

class A {
    constructor() {console.log('constructor');}
    a() {}
}

const array = [A];

new (array[0])(); // Prints 'constructor'
Run Code Online (Sandbox Code Playgroud)

我想使用接口使数组类型安全。这是我在 TypeScript 中实现这一点的尝试:

interface I {
    a();
}

class A implements I {
    constructor() {console.log('constructor')}
    a() {}
}

const array: I[] = [A];

new (array[0])();
Run Code Online (Sandbox Code Playgroud)

当我编译这个时,我收到以下错误:

Error:(16, 21) TS2322: Type 'typeof A' is not assignable to type 'I'.
  Property 'a' is missing in type 'typeof A'.
Run Code Online (Sandbox Code Playgroud)

因为此错误消息提到typeof A is not assignable to type 'I',所以数组似乎不能包含类,就像typeof用于实例化对象一样。

我需要的是一种将所有类分组到单个变量中而不实例化它们的方法,并且能够通过索引访问类。我怎样才能在 TypeScript 中实现这一点?

Chr*_*jen 5

接口定义了实例上可用的属性和方法,因此这可以工作:

 const array: I[] = [new A()];
Run Code Online (Sandbox Code Playgroud)

这不是您想要的,但它应该展示为什么它不起作用:类和实例是两个不同的东西。

你想说的是“它是一个类型数组,new()将返回 I 的一个实例”。

我认为它应该看起来像这样:

class Test implements I {
    a() {}
}

interface I {
    a();
}

interface TI {
    new (): I;
}

const arr: TI[] = [Test];

const inst = new arr[0]();
Run Code Online (Sandbox Code Playgroud)