I have an abstract class A. Then I have two classes, B and C, that extend that abstract class.
(Example code):
abstract class A {
private name: string;
abstract saluto(): void;
constructor(name: string) {
this.name = name;
}
}
class B {
saluto(): void {
console.log(`Hello ${this.name}`);
}
constructor(name: string) {
super(name);
}
}
class C {
saluto(): void {
console.log(`Ciao ${this.name}`);
}
constructor(name: string) {
super(name);
}
}
I have a function that given the array const generators = [B, C] and a parameter returns me the instances of B and C created passing the parameter to the constctor.
For instance:
const generators = [B, C];
function generate(generators: typeof A[], name: string): A[] {
return generators.map(gen => new gen(name)); // Here I have the error
}
const instances = generate(generators, 'Eugenio');
Here I have an error, because it says Cannot create an instance of an abstract class..
How can I solve this problem? There should be a way to tell to tsc that the generators are not A itself but non-abstract classes that extends it.