Access to static properties via this.constructor in typescript

前端 未结 6 2290
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-18 13:49

I want to write es6 class:

class SomeClass {
    static prop = 123

    method() {
    }
}

How to get access to static prop from <

6条回答
  •  遇见更好的自我
    2021-02-18 14:30

    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

提交回复
热议问题