I am puzzled by the structure of 3 classes: A, B, and C. Both B and C extend the abstract class A.
abstract class A {
public name: string;
constructor(name: string) {
this.name = name;
}
abstract getName(): string;
}
class B extends A {
getName(): string {
return "B: " + this.name;
}
}
class C extends A {
getName(): string {
return "C: " + this.name;
}
}
In an attempt to create a subclass of an abstract class at runtime using the code below, I encountered a compiler error stating: "Cannot create an instance of an abstract class."
const classes: { [type: string]: typeof A } = {
b: B,
c: C,
};
function test(type: string, name: string) {
if (!classes.hasOwnProperty(type)) {
throw new Error(`Invalid type: ${type}`);
}
const _class = classes[type];
return new _class("name"); // compiler error: Cannot create an instance of abstract class.
}
let x = test("b", "bob");
console.log(x.getName());
If I modify the classes
definition to
{ [type: string]: typeof B | typeof C }
, it functions properly.
const classes: { [type: string]: typeof B | typeof C } = {
b: B,
c: C,
};
function test(type: string, name: string) {
if (!classes.hasOwnProperty(type)) {
throw new Error(`Invalid type: ${type}`);
}
const _class = classes[type];
return new _class("name");
}
let x = test("b", "bob");
console.log(x.getName());
This method may lead to a rapid increase in the definition list like
typeof B | typeof C | typeof D | typeof E | etc.
. Is there a more sophisticated approach to manage this situation?