2017-06-20 109 views
0

我有一个由多个子类扩展的基类。现在我想要将父类的类型作为属性的类型。所有的孩子类型都应该是有效的。我已经尝试过typeof,但不起作用。关于如何将基类的类型作为属性的类型的任何想法?为什么我要的类型的引用的原因是,我希望能够创建类的新实例,例如新test.componentType()应该创建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 
+0

有没有必要要使用typeof,只需使用父 – toskv

+2

在任何类中,只需使用'this.constructor.prototype'即可获得父类。从您的问题中不清楚为什么您需要在界面中定义该属性。 – artem

+1

现在编辑该问题 – Abris

回答

2

你的代码是不起作用,因为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(); 
+0

非常感谢你的回答:) {new(... args):Parent};解决了它。 – Abris

+1

确实,你需要'(... args)'来捕获带有非空参数列表的构造函数。 –