I have a base class which is extended by several child classes. Now I want to have the type of the parent class as the type of a property. All child types should be valid aswell. I have tried typeof but that doesn't work. Any ideas on how to have the type of a base class as the type for a property? The reason why I want a reference to the type is that I want to be able to create new instances of the Class, for example new test.componentType() should create a new instance of Child2
class Parent {
}
class Child1 extends Parent {
}
class Child2 extends Parent {
}
interface Config {
componentType: typeof Parent;
}
const test: Config = {
componentType: typeof Child2
}
new test.componentType() -> should create a new instance of Child2
Your code was not working because Child2
is already the class object, which is compatible with typeof Parent
. test
should have been defined like this:
const test: Config = {
componentType: Child2
}
Nevertheless, you seem to just want the field componentType
to hold a constructor. In that case, you can make componentType
prototyped as an object with the new
method:
interface Config {
componentType: { new(): Parent };
}
const test: Config = {
componentType: Child2
}
const myinstance: Parent = new test.componentType();
To retain information about the constructed instance types, a generic type can be used:
interface Config<T extends Parent> {
componentType: { new(): T };
}
const test = {
componentType: Child2
}
const myinstance: Child2 = new test.componentType();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With