Access to static properties via this.constructor in typescript

Artur Eshenbrener picture Artur Eshenbrener · Oct 28, 2015 · Viewed 8.1k times · Source

I want to write es6 class:

class SomeClass {
    static prop = 123

    method() {
    }
}

How to get access to static prop from method() without use SomeClass explicitly? In es6 it can be done with this.constructor, but in typescript this.constructor.prop causes error "TS2339: Property 'prop' does not exist on type 'Function'".

Answer

basarat picture basarat · Oct 29, 2015

but in typescript this.constructor.prop causes error "TS2339: Property 'prop' does not exist on type 'Function'".

Typescript does not infer the type of constructor to be anything beyond Function (after all ... the constructor might be a sub class).

So use an assertion:

class SomeClass {
    static prop = 123;
    method() {
        (this.constructor as typeof SomeClass).prop;
    }
}

More on assertions