Is there a way to inject a subclass into a class during its constructor using TypeScript?
I've tried to demonstrate my idea with some pseudo-code here:
type GenericConstructor<T> = { new (): T; }
class MyClass {
constructor(
SubClass: GenericConstructor
) {
this.subclass = new SubClass();
}
}
class MySubClass1 {}
class MySubClass2 {}
const withSubClass1 = new MyClass(MySubClass1);
const withSubClass2 = new MyClass(MySubClass2);
The issue is that TypeScript doesn't seem to allow specifying a generic parameter for a constructor. I think I might be missing something here.
My goal is to have a class (MyClass
) that can accept a generic child class which meets specific interface requirements. Maybe defining an interface would be the right approach, but I'm not sure how to go about it.
Thank you in advance for your assistance!