我想写es6类:
class SomeClass {
static prop = 123
method() {
}
}
如何在不使用prop
的情况下从method()
访问静态SomeClass
?在es6中,它可以用this.constructor
完成,但在typescript中this.constructor.prop
导致错误“TS2339:属性'prop'在类型'Function'上不存在”。
但是在typescript中this.constructor.prop导致错误“TS2339:属性'prop'在类型'Function'上不存在”。
Typescript不会将constructor
的类型推断为Function
之外的任何东西(毕竟......构造函数可能是一个子类)。
所以使用断言:
class SomeClass {
static prop = 123;
method() {
(this.constructor as typeof SomeClass).prop;
}
}
微软程序员谈论这个,但没有一个很好的方式来键入constructor
。您可以先使用此提示。
class SomeClass {
/**
* @see https://github.com/Microsoft/TypeScript/issues/3841#issuecomment-337560146
*/
['constructor']: typeof SomeClass
static prop = 123
method() {
this.constructor.prop // number
}
}
它有点脏,但这个代码在Typescript Playground中适用于我:
class SomeClass {
static prop = 123;
constructor() {
console.log(this.constructor["prop"]);
}
}
var a = new SomeClass();
通常简单的方法是:
class SomeClass {
static prop = 123
method() {
console.log(SomeClass.prop) //> 123
}
}
请注意,如果使用此方法,SomeClass
的子类将直接访问SomeClass.prop
而不是SomeSubClass.prop
。如果希望子类访问自己的同名静态属性,请使用basarat的方法。
通过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;
}
我想你将来想要扩展这个课程。所以最好这样做:
class SomeClass<T extends typeof SomeClass = typeof SomeClass> {
static prop = 123
method() {
(this.constructor as T).prop;
}
}