在TypeScript中定义的类.constructor

jds*_*816 9 typescript

export class Entity {
    add(component: Component, componentClass?: { new (): Component;}): Entity {
        if (!componentClass) {
            componentClass = component.constructor
        }

        /** sniiiiip **/
    }
}
Run Code Online (Sandbox Code Playgroud)

示例的第4行(分配component.constructor)导致编译器抱怨:

属性'构造函数'不存在于'Component'类型的值上

获取对象构造函数的引用的正确方法是什么?我的理解是,JavaScript中的所有对象都有一个.constructor属性,该属性指向用于创建该对象的构造函数...

Rya*_*ugh 8

这在类型代码中很少见,默认情况下它不包含在定义中Object.您可以简单地转换为any:

componentClass = (<any>component).constructor;
Run Code Online (Sandbox Code Playgroud)