如何传递构造函数数组

SET*_*SET 5 typescript

如何传递返回某种类型对象的函数数组.换句话说 - 构造函数数组?

我想做的是这样的:

    constructor(name: string, systems: Array<Function>){
        this.system = new systems[0]();
    }
Run Code Online (Sandbox Code Playgroud)

但我得到一个错误Cannot use 'new' with an expression whose type lacks a call or construct signature.,据我所知,我应该以某种方式让编译器知道构造函数返回的对象类型,但我不知道如何.

假设RJM的回答,这是我的意思的一个扩展示例:

interface System{
    name: string;
}
interface Component{
    blahblha: string;
}
class Doh implements Component{
    blahblha: string;
}
class Bar implements System{
    name: string = 'bar';
} 

class Blah implements System{
    name: string = 'foo';
}
class Foo {
    systems: Array<System>;
    constructor(bars: Array<()=>System>) {
        for (let i in bars){
            this.systems.push(new bars[i]()); // error: only a void functions can be called with the 'new' keyword.
        }
    }
}
var foo = new Foo([Blah]); // error: Argument of type 'typeof Blah[]' is not assignable to parameter of type '(() => System[]'. Type 'typeof Blah[]' is not assignable to type '() => System'.
Run Code Online (Sandbox Code Playgroud)

我想确保Foo.systems仅使用实现System接口的对象实例填充.所以我应该有错误做某事,new Foo([Doh]);但即使在通过时我也会收到错误Blah

tos*_*skv 6

如果要实例化类,则必须使用new关键字引用它的构造函数.

function factory(constructors: { new (): System }[]) {
    let constructed = constructors.map(c => new c());
}

interface System {
    name: string;
}
class SomeClass implements System {
    name: string;
    constructor() { }
}

class SomeOtherClass implements System {
    name: string;
    constructor() { }
}

let a = factory([SomeClass, SomeClass, SomeClass, SomeOtherClass]);
Run Code Online (Sandbox Code Playgroud)

工厂的功能将得到的满足,可以创造一些构造函数列表系统接口.

使用未实现System的类调用该方法将导致您现在收到的错误.

class AnotherClass {}
factory([AnotherClass]); // error
Run Code Online (Sandbox Code Playgroud)

结构类型也可以,因此您不必显式实现接口.

class AnotherClass {
    name: string
}
factory([AnotherClass]);
Run Code Online (Sandbox Code Playgroud)

为了使代码更清洁,您可以将为constructors参数描述的接口移动到接口声明.

// an interface that describes classes that create instances that satisfy the System interface
interface CreatesSystem {
    new (): System
}

interface System {
    name: string;
}

function factory(constructors: CreatesSystem[]) {
    let constructed = constructors.map(c => new c());
}
Run Code Online (Sandbox Code Playgroud)