Through collaboration with a fellow coder on StackOverflow, I have mastered the art of specifying a constructor as an argument to a class:
type GenericConstructor<T> = { new(): T; }
class MyClass<T> {
subclass: T;
constructor(
SubClass: GenericConstructor<T>
) {
this.subclass = new SubClass();
}
}
class MySubClass1 { a = "" }
class MySubClass2 { b = "" }
const withSubClass1 = new MyClass(MySubClass1);
const withSubClass2 = new MyClass(MySubClass2);
If feasible, I now aim to incorporate a default SubClass
so that users of MyClass
have the option to use the default functionality without specifying a subclass.
Below is the code in which I tried to implement this feature (unfortunately without success):
type GenericConstructor<T> = { new(): T; }
class DefaultSubClass { c = "" }
class MyClass<T> {
subclass: T;
constructor(
SubClass: GenericConstructor<T> = DefaultSubClass // <== error!!
) {
this.subclass = new SubClass();
}
}
// …sliced out for brevity
Upon execution, TypeScript throws the following error at me:
Type 'typeof DefaultSubClass' is not assignable to type 'GenericConstructor<T>'.
Type 'DefaultSubClass' is not assignable to type 'T'.
'DefaultSubClass' can be assigned to the constraint of type 'T', however 'T' might be instantiated with a different subtype of constraint '{}'.
Grateful for all the advice and assistance provided as always.