【问题标题】:error TS2356 says Number type variable must be an arithmetic operand of type 'number'错误 TS2356 说数字类型变量必须是“数字”类型的算术操作数
【发布时间】:2018-11-08 17:45:11
【问题描述】:

这是我的类定义的样子:

timeLeft: Number;

constructor() { 
    this.timeLeft = 60;
  }

  start() {
    console.log(typeof(this.timeLeft)); // prints out 'number'

    setInterval(() => {

      this.timeLeft--; // error TS2356 occurs here
      console.log(this.timeLeft);

    }, 1000);
  }

  ngOnInit() {}

控制台:

错误 TS2356:算术操作数的类型必须为“任意”、“数字”或枚举类型。

【问题讨论】:

  • 我的 Typescript 很糟糕,但粗略浏览一下文档表明 timeLeft 的类型应该是 number,而不是 Number

标签: javascript typescript setinterval


【解决方案1】:

正如 Phil 在评论部分提到的,最好使用“数字”而不是“数字”。 “数字”是指在 JavaScript 代码中几乎从未适当使用的非原始装箱对象。 参考:Do's and Don'ts

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-23
    • 2019-02-04
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 2019-08-16
    • 1970-01-01
    • 2021-06-11
    相关资源
    最近更新 更多