简体   繁体   English

错误 TS2339:“温度”类型上不存在属性“摄氏度”

[英]error TS2339: Property 'celsius' does not exist on type 'Temperature'

I'm trying to make a Temperature class with typescript.我正在尝试使用 typescript 制作温度 class。 The javascript version works, but typescript throws this error. javascript 版本有效,但 typescript 抛出此错误。 Why does this example work with javascript, but fail with typescript?为什么此示例适用于 javascript,但适用于 typescript? Here's the code to reproduce:这是要重现的代码:

Temperature.js温度.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);

Temperature.ts温度.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);

Successful javascript output:成功 javascript output:

➜  ch6 node Temperature.js 
100
212
➜  ch6 

Compilation error:编译错误:

➜  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.

In a typescript class, we need to declare properties for them to compile correctly.在 typescript class 中,我们需要为它们声明属性才能正确编译。 See here for an example from the docs.有关文档中的示例,请参见此处 When I add the property declaration, the file compiles successfully.当我添加属性声明时,文件编译成功。

Temperature.ts温度.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);

Compilation success:编译成功:

➜  ch6 tsc --target es6 Temperature.ts
➜  ch6  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM