问题描述
demo代码:
let uid = 0;
Class Dep{
constructor(){
this.id = uid++; // vscode编译器报错
}
}
使用vscode编写typeScript文件,使
this.id
赋值时会提示报错,报错信息如下:
error : Property 'id' does not exist on type 'Dep'.ts(2339)
官网:
2339
:错误 Property '{0}' does not exist on type '{1}'.
类型“{1}”上不存在属性“{0}”。
通过官网解释可以知道:
TS是静态类型的语言,就像我们用java类的语言,一定要提前定义,未定义的属性直接调用会报错。
解决办法1
第一种解决办法:将this.id
改为(this as any):id = uid++
;
let uid = 0;
Class Dep{
constructor(){
(this as any).id = uid++;
}
}
解决办法2
第二种解决办法:将this.id
改为this["id"] = uid++
;
let uid = 0;
Class Dep{
constructor(){
this["id"] = uid++;
}
}
解决办法3
除了以上的解决办法外,还有个最优解,根据提示我们是知道TS没有定义的语言不能直接调用,那么我们就在类里,定义类内的属性再去调用就可以解决了。
第三种解决办法:
let uid = 0;
Class Dep{
id: number;
constructor(){
this.id = uid++;
}
}