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

时间:2019-11-21 01:44:30

标签: javascript typescript

我正在尝试使用打字稿制作温度类。 javascript版本有效,但打字稿会引发此错误。为什么此示例可与javascript一起使用,而对打字稿却无法使用?这是要复制的代码:

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

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输出:

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

1 个答案:

答案 0 :(得分:0)

在打字稿类中,我们需要声明属性以使其能够正确编译。有关文档的示例,请参见here。添加属性声明后,文件将成功编译。

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