Access to static properties via this.constructor in typescript

前端 未结 6 2274
爱一瞬间的悲伤
爱一瞬间的悲伤 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:35

    Accessing static properties through this.constructor (as opposed to just doing SomeClass.prop like normally you would) is only ever useful when you don't know the name of the class and have to use this instead. typeof this doesn't work, so here's my workaround:

    class SomeClass {
    
      static prop = 123;
    
      method() {
    
        const that = this;
    
        type Type = {
          constructor: Type;
          prop: number; //only need to define the static props you're going to need
        } & typeof that;
    
        (this as Type).constructor.prop;
      }
    
    }
    

    Or, when using it outside the class:

    class SomeClass {
      static prop = 123;
      method() {
        console.log(
          getPropFromAnyClass(this)
        );
      }
    }
    
    function getPropFromAnyClass(target: T) {
      type Type = {
        constructor: Type;
        prop: number; //only need to define the static props you're going to need
      } & T;
    
      return (target as Type).constructor.prop;
    }
    

提交回复
热议问题