我有一个抽象类Base
,它接受<T>
要在类中使用的类型变量。然后我有很多明确定义类型的派生类,比如class Derived extends Base<string> {...}
我想要一个变量(或变量数组),其类型可以是任何派生类,不管是什么<T>
。然后我希望能够使用该变量来创建这些派生类的新实例。
这是我尝试过的一些代码。从那里,我迷路了。
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 obviously works too, but with many derived classes can get long and tedious
let classes_B: (typeof Derived | typeof SecondDerived)[] = [];
classes_B.push(Derived);
classes_B.push(SecondDerived);
// This does NOT work
let classes_C: Base<any>[] = [];
classes_C.push(Derived); // "typeof Derived is not assignable to type Base<any>"
// This does NOT work
let classes_D: Base<unknown>[] = [];
classes_D.push(Derived); // "typeof Derived is not assignable to type Base<unknown>"
// This does NOT work
let classes_E: Base<string>[] = [];
classes_E.push(Derived); // "typeof Derived is not assignable to type Base<string>"
// This does NOT work
let classes_F: (typeof Base)[] = [];
classes_F.push(Derived); // "typeof Derived is not assignable to typeof Base"