Art*_*ner 19 static-methods this static-members typescript typescript1.6
我想写es6类:
class SomeClass {
static prop = 123
method() {
}
}
Run Code Online (Sandbox Code Playgroud)
如何获得访问静态prop从method()没有使用SomeClass明确?在es6中它可以完成this.constructor,但是在打字稿中this.constructor.prop导致错误" TS2339:属性'道具'在类型'函数'上不存在 ".
bas*_*rat 18
但是在typescript中this.constructor.prop导致错误"TS2339:属性'prop'在类型'Function'上不存在".
Typescript不会推断出constructor超越的类型Function(毕竟...构造函数可能是一个子类).
所以使用断言:
class SomeClass {
static prop = 123;
method() {
(this.constructor as typeof SomeClass).prop;
}
}
Run Code Online (Sandbox Code Playgroud)
Microsoft程序员正在谈论这一点,但是没有一个很好的输入方法constructor。您可以先使用此技巧。
class SomeClass {
/**
* @see https://github.com/Microsoft/TypeScript/issues/3841#issuecomment-337560146
*/
['constructor']: typeof SomeClass
static prop = 123
method() {
this.constructor.prop // number
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4624 次 |
| 最近记录: |