通过typescript中的this.constructor访问静态属性
我想写es6课程:通过typescript中的this.constructor访问静态属性,typescript,this,static-methods,static-members,typescript1.6,Typescript,This,Static Methods,Static Members,Typescript1.6,我想写es6课程: class SomeClass { static prop = 123 method() { } } 如何从method()访问静态prop,而不显式使用SomeClass?在es6中,可以使用this.constructor,但在typescript中,this.constructor.prop会导致错误“TS2339:type'Function'上不存在属性'prop'。有点脏,但此代码在以下情况下对我有效: 但在typescript中,thi
class SomeClass {
static prop = 123
method() {
}
}
如何从
method()
访问静态prop
,而不显式使用SomeClass
?在es6中,可以使用this.constructor
,但在typescript中,this.constructor.prop
会导致错误“TS2339:type'Function'上不存在属性'prop'。有点脏,但此代码在以下情况下对我有效:
但在typescript中,this.constructor.prop会导致错误“TS2339:类型“Function”上不存在属性“prop”
Typescript不会推断构造函数的类型
超出函数
(毕竟,构造函数可能是一个子类)
因此,请使用断言:
class SomeClass {
static prop = 123;
method() {
(this.constructor as typeof SomeClass).prop;
}
}
通常最简单的方法是:
class SomeClass {
static prop = 123
method() {
console.log(SomeClass.prop) //> 123
}
}
请注意,如果使用此选项,
SomeClass
的子类将直接访问SomeClass.prop
,而不是SomeSubClass.prop
。如果您想让子类访问它们自己的同名静态属性,请使用basarat的方法。Microsoft程序员正在谈论这一点,但键入构造函数并不是一个好方法。你可以先使用这个技巧
class SomeClass {
/**
* @see https://github.com/Microsoft/TypeScript/issues/3841#issuecomment-337560146
*/
['constructor']: typeof SomeClass
static prop = 123
method() {
this.constructor.prop // number
}
}
通过this.constructor
访问静态属性(而不是像通常那样只做SomeClass.prop
)只有在您不知道类的名称并且必须使用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{
静态道具=123;
方法(){
console.log(
getPropFromAnyClass(此)
);
}
}
函数getPropFromAnyClass(目标:T){
类型类型={
构造函数:类型;
prop:number;//只需要定义需要的静态道具
}&T;
返回(目标为类型).constructor.prop;
}
我猜您希望将来扩展这个类。因此,最好这样做:
class-SomeClass{
静态道具=123
方法(){
(此构造函数为T)prop;
}
}
您尝试过“this.constructor[“prop”]”吗?这不是一个解决方案:在这种情况下,我完全错过了chek类型。我想在访问不存在的属性时出错。你能共享你的实际代码吗?你想在什么环境下做这件事?@ArturEshenbrener你可以做(this.constructor作为SomeClass的类型)。prop
,但这有什么意义呢?为什么不使用SomeClass.prop
?元素隐式地具有“any”类型,因为类型“Function”没有索引签名。
当“no implicit any”设置为ON时,问题状态为“未显式使用SomeClass”。我不明白这是如何提供答案的。
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;
}