Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript typeof class and derived classes

Tags:

typescript

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
like image 423
Abris Avatar asked Jun 20 '17 12:06

Abris


1 Answers

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();
like image 111
E_net4 stands with Ukraine Avatar answered Oct 14 '22 13:10

E_net4 stands with Ukraine