Within my abstract class Base
, I utilize a type variable <T>
to define the type for the class. I have numerous derived classes that explicitly specify the type, like
class Derived extends Base<string> {...}
I aim to have a variable (or an array of variables) that can accept any of these derived classes, regardless of the <T>
. Furthermore, I want to be able to use this variable to instantiate new instances of these Derived classes.
Below is my attempt at some code. However, I am stuck at this point.
abstract class Base<T> {
abstract value: T;
}
class Derived extends Base<string> {
value = 'Hello world!';
}
class SecondDerived extends Base<number> {
value = 1234;
}
// This has type (typeof Derived | typeof SecondDerived)
let classes_A = [Derived, SecondDerived];
// This also works, but can become lengthy with multiple derived classes
let classes_B: (typeof Derived | typeof SecondDerived)[] = [];
classes_B.push(Derived);
classes_B.push(SecondDerived);
// The following scenarios do NOT work
let classes_C: Base<any>[] = [];
classes_C.push(Derived); // "typeof Derived is not assignable to type Base<any>"
let classes_D: Base<unknown>[] = [];
classes_D.push(Derived); // "typeof Derived is not assignable to type Base<unknown>"
let classes_E: Base<string>[] = [];
classes_E.push(Derived); // "typeof Derived is not assignable to type Base<string>"
let classes_F: (typeof Base)[] = [];
classes_F.push(Derived); // "typeof Derived is not assignable to typeof Base"