When working with TypeScript, I'm attempting to correctly type a variable that is an "Array of Classes inheriting from a base class".
The code I have results in the error 'Cannot create an instance of an abstract class. ts(2511)', which makes sense. However, my intention is not to instantiate a member of Base, but rather 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 can I accurately type const list: ???[] = [A, B];
Switching to const list: typeof A[] = [A,B]
works, but it wrongly suggests that all entries in the list are of type A
.