type为参数的typescript方法

Cec*_*Cec 5 class typescript

鉴于此课程的层次性

export class A {
  static m() { return 'a'};
}


export class B extends A {
  static m() { return 'b'};
}


export class C extends A {
  static m() { return 'c'};
}
Run Code Online (Sandbox Code Playgroud)

我需要一个方法,取一个类(不是实例)扩展A并调用m()数组的每个元素:

function looper(classes: A[]) {
  classes.forEach(c => c.m());
}
Run Code Online (Sandbox Code Playgroud)

这需要A或其子类的实例数组.

我怎样才能有一个方法作为扩展A的参数类?

@Oscar Paz指出泛型

编辑1

此外,looper的输入需要存储在对象的属性中:

export class Container {
  public klazzes: A[];
}
Run Code Online (Sandbox Code Playgroud)

一世

Osc*_*Paz 5

好吧,使用泛型:

function callM<T extends typeof A>(arr: T[]): void {
    arr.forEach(t => t.m());
}
Run Code Online (Sandbox Code Playgroud)

现在你可以这样做:

callM([A, B, C]); // OK
callM([A, B, string]); // Error
Run Code Online (Sandbox Code Playgroud)

如果要存储值:

class Container {
    public klazzes: (typeof A)[];
}
const cont: Container = new Container();
callM(cont.klazzes);
Run Code Online (Sandbox Code Playgroud)