通过typescript中的this.constructor访问静态属性

问题描述 投票:11回答:6

我想写es6类:

class SomeClass {
    static prop = 123

    method() {
    }
}

如何在不使用prop的情况下从method()访问静态SomeClass?在es6中,它可以用this.constructor完成,但在typescript中this.constructor.prop导致错误“TS2339:属性'prop'在类型'Function'上不存在”。

typescript this static-methods static-members typescript1.6
6个回答
16
投票

但是在typescript中this.constructor.prop导致错误“TS2339:属性'prop'在类型'Function'上不存在”。

Typescript不会将constructor的类型推断为Function之外的任何东西(毕竟......构造函数可能是一个子类)。

所以使用断言:

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

More on assertions


5
投票

微软程序员谈论这个,但没有一个很好的方式来键入constructor。您可以先使用此提示。

class SomeClass {
    /**
     * @see https://github.com/Microsoft/TypeScript/issues/3841#issuecomment-337560146
     */
    ['constructor']: typeof SomeClass

    static prop = 123

    method() {
        this.constructor.prop // number
    }
}

0
投票

它有点脏,但这个代码在Typescript Playground中适用于我:

class SomeClass {
    static prop = 123;

    constructor() {
        console.log(this.constructor["prop"]);
    }

}

var a = new SomeClass();

0
投票

通常简单的方法是:

class SomeClass {
    static prop = 123

    method() {
        console.log(SomeClass.prop)  //> 123
    }
}

请注意,如果使用此方法,SomeClass的子类将直接访问SomeClass.prop而不是SomeSubClass.prop。如果希望子类访问自己的同名静态属性,请使用basarat的方法。


0
投票

通过this.constructor访问静态属性(而不是像通常那样只执行SomeClass.prop)只有在您不知道类的名称并且必须使用this时才有用。 typeof this不起作用,所以这是我的解决方法:

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;
  }

}

或者,在课外使用时:

class SomeClass {
  static prop = 123;
  method() {
    console.log(
      getPropFromAnyClass(this)
    );
  }
}

function getPropFromAnyClass<T>(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;
}

0
投票

我想你将来想要扩展这个课程。所以最好这样做:

class SomeClass<T extends typeof SomeClass = typeof SomeClass> {
    static prop = 123

    method() {
        (this.constructor as T).prop;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.