Home > Software engineering >  How to define a method param type in order to accept multiple class names in Typescript?
How to define a method param type in order to accept multiple class names in Typescript?

Time:04-08

I want to pass as a param of an argument the value below:

const myClassesArray = [MyClass1, MyClass2, MyClass3];

I cannot change the classes in the array in order to f.e. make all them extend or implement any other class or interface.

Therefore the method be like this:

myMethod(myClasses){
    // for each myClasses
        new myClasses[i]();
    // for end
}

Usage example:

myMethod(myClassesArray);

Am I able to do it in TS?

CodePudding user response:

You can do this via constructable function signatures. Here is how it would look like in your code:

class A {
    constructor(input: string) {}
}

class B {
    constructor(input: string) {}
}

class C {
    constructor(input: string) {}
}

function comboParser(parsers: (new (input: string) => any)[]) {
    for (const parser of parsers) {
        const p = new parser("hey");
    }
}

//            
  • Related