In TypeScript I'm trying to correctly type a variable of type "Array of Classes inheriting from a base class".
Using this code I get the error 'Cannot create an instance of an abstract class. ts(2511)' which I understand. But I don't want to instantiate a member of Base, just its descendants.
abstract class Base {
abstract execute(param: string): void;
protected name: string;
constructor(name: string) {
this.name = name;
}
public commonMethod() {
console.log("Common Method");
}
}
class A extends Base {
execute() {
console.log(`Hello from A, ${this.name}`);
this.commonMethod();
}
}
class B extends Base {
execute() {
console.log(`Hello from B, no-name`);
}
}
const list: typeof Base[] = [A, B];
const names = ["Phil", "Andy", "Bob"];
names.map((name) => list.map((cl) => new cl(name)));
How would I correctly type const list: ???[] = [A, B];
When I switch to const list: typeof A[] = [A,B] it works but then suggests all list entries are A which they are not.