問題描述
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++;
}
}