Typescript typeof class and derived classes

时间:2017-06-20 12:39:59

标签: 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

1 个答案:

答案 0 :(得分:5)

您的代码无效,因为Child2已经是类对象,它与typeof Parent兼容。 test应该像这样定义:

const test: Config = {
    componentType: Child2
}

尽管如此,您似乎只希望字段componentType包含构造函数。在这种情况下,您可以使用componentType方法将new原型化为对象:

interface Config {
    componentType: { new(): Parent };
}

const test: Config = {
    componentType: Child2
}

const myinstance: Parent = new test.componentType();

保留有关构造的实例类型的信息,这是一种泛型类型  可以使用:

interface Config<T extends Parent> {
    componentType: { new(): T };
}

const test = {
    componentType: Child2
}

const myinstance: Child2 = new test.componentType();