Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access .constructor of class defined in TypeScript

Tags:

typescript

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

        /** sniiiiip **/
    }
}

Line 4 of the example (assigning component.constructor) causes the compiler to complain that:

The property 'constructor' does not exist on value of type 'Component'

What's the proper way to get a reference to an objects constructor? My understanding is that all Objects in JavaScript have a .constructor property that points to the constructor used to create that object...

like image 864
jdsmith2816 Avatar asked Nov 28 '12 04:11

jdsmith2816


1 Answers

This is rare enough in typed code that it's not included by default on the definition of Object. You can simply cast to any instead:

componentClass = (<any>component).constructor;
like image 56
Ryan Cavanaugh Avatar answered Sep 19 '22 23:09

Ryan Cavanaugh