'How to define a method param type in order to accept multiple class names in Typescript?
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?
Solution 1:[1]
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");
}
}
// ? these work
comboParser([A, B]);
comboParser([A]);
// ? these fail
comboParser([""]);
comboParser([A, ""]);
comboParser([B, C, 5]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sno2 |
