How to pass an array of constructors

How can I pass an array of functions that return an object of some type. In other words, an array of constructors?

I want to do something like this:

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

but I received an error message Cannot use 'new' with an expression whose type lacks a call or construct signature., and as I understand it, I have to somehow tell the compiler what type of objects is returned to the constructor, but I don’t know how to do it.

Assuming RJM's answer , here is a slightly extended example of what I mean:

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'.

I want to make sure that Foo.systemsonly instances of objects that implement the system interface will be populated. So I have to make a mistake doing something like new Foo([Doh]);, but I get an error even when transferringBlah

+4
source share
2

, 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]);

factory , - , .

, , , .

class AnotherClass {}
factory([AnotherClass]); // error

, .

class AnotherClass {
    name: string
}
factory([AnotherClass]);

, , , .

// 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());
}
+5

, , , .

function constructor(name: string, systems: Array<() => void>){
    this.system = new systems[0]();
}
0

Source: https://habr.com/ru/post/1623663/


All Articles