[英]Error TS2339: Property 'Default' does not exist on type 'string'.**
[英]error TS2339: Property 'celsius' does not exist on type 'Temperature'
我正在嘗試使用 typescript 制作溫度 class。 javascript 版本有效,但 typescript 拋出此錯誤。 為什么此示例適用於 javascript,但適用於 typescript? 這是要重現的代碼:
溫度.js
class Temperature {
constructor(celsius) {
this.celsius = celsius;
}
get fahrenheit() {
return this.celsius * 1.8 + 32;
}
set fahrenheit(value) {
this.celsius = (value - 32) / 1.8;
}
static fromFahrenheit(value) {
return new Temperature((value - 32) / 1.8);
}
}
let test = new Temperature(100);
console.log(test.celsius);
console.log(test.fahrenheit);
溫度.ts
class Temperature {
constructor(celsius) {
this.celsius = celsius;
}
get fahrenheit() {
return this.celsius * 1.8 + 32;
}
set fahrenheit(value) {
this.celsius = (value - 32) / 1.8;
}
static fromFahrenheit(value) {
return new Temperature((value - 32) / 1.8);
}
}
let test = new Temperature(100)
console.log(test.celsius);
console.log(test.fahrenheit);
成功 javascript output:
➜ ch6 node Temperature.js
100
212
➜ ch6
編譯錯誤:
➜ ch6 tsc --target es6 Temperature.ts
Temperature.ts:3:10 - error TS2339: Property 'celsius' does not exist on type 'Temperature'.
3 this.celsius = celsius;
~~~~~~~
Temperature.ts:6:17 - error TS2339: Property 'celsius' does not exist on type 'Temperature'.
6 return this.celsius * 1.8 + 32;
~~~~~~~
Temperature.ts:9:10 - error TS2339: Property 'celsius' does not exist on type 'Temperature'.
9 this.celsius = (value - 32) / 1.8;
~~~~~~~
Temperature.ts:18:18 - error TS2339: Property 'celsius' does not exist on type 'Temperature'.
18 console.log(test.celsius);
~~~~~~~
Found 4 errors.
在 typescript class 中,我們需要為它們聲明屬性才能正確編譯。 有關文檔中的示例,請參見此處。 當我添加屬性聲明時,文件編譯成功。
溫度.ts
class Temperature {
celsius: number;
constructor(celsius) {
this.celsius = celsius;
}
get fahrenheit() {
return this.celsius * 1.8 + 32;
}
set fahrenheit(value) {
this.celsius = (value - 32) / 1.8;
}
static fromFahrenheit(value) {
return new Temperature((value - 32) / 1.8);
}
}
let test = new Temperature(100)
console.log(test.celsius);
console.log(test.fahrenheit);
編譯成功:
➜ ch6 tsc --target es6 Temperature.ts
➜ ch6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.