类中的 Typescript 联合类型

标签 typescript

我有一个关于在类中设置联合类型的简单示例。

class Foo {
  constructor() {}
  progress: number | string = 0;

  bar() {
        this.progress = this.progress + 5;
    }
}

我希望增加 5,但我收到了 ts(2365) 错误。

Operator '+' cannot be applied to types 'string | number' and '5'.ts(2365)

我认为这会起作用,因为如果我像下面的代码那样在类之外设置它。

let progress: number | string = 0;
progress = progress + 5;

没有错误。

最终,我要做的是在类声明中设置一个变量,该变量接受来自 setInterval 的数字。 ,所以我试图将变量设置为联合类型的数字和 NodeJS.TimersetInterval返回 NodeJS.Timer .

export class CurrentTrainingComponent implements OnInit {
  interval: number | NodeJS.Timer;
  progress: number = 0;

  constructor() {}

  ngOnInit() {
    this.interval = setInterval(() => {
      this.progress = this.progress + 5;
      if (this.progress >= 100) {
        clearInterval(this.interval);
      }
    }, 100);
  }

  onStop() {
    clearInterval(this.interval);
  }
}

我知道我可以简单地分配 <any>解决这个问题this.interval = <any>setInterval( ()=>{} ) , 但我想看看我是否可以尝试 Union 类型。

与此问题无关的最后一件事,设置 <number>setInterval显示警告 Conversion of type 'Timer' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.ts(2352)

最佳答案

在 bar 函数中,你不能确定你现在的值是一个数字。 您可以添加额外的检查以使其工作

class Foo {
    constructor() {}
    progress: number | string = 0;

    bar() {
        if (typeof this.progress === 'number')
            this.progress = this.progress + 5;
    }
}

如果是

let progress: number | string = 0;
progress = progress + 5;

value 肯定是一个数字(它在上面被分配了 1 行)

关于类中的 Typescript 联合类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56026681/

相关文章:

typescript 错误 : tsc: command not found

javascript - 如何从 AngularJS 指令调用 Android 方法?

typescript - 将不正确的变量类型传递给函数不会发出类型错误

reactjs - typescript / react : How can a ref be added to a material-ui Box component?

javascript - 如何确定 Observable.merge 中哪些 observable 发生了更改?

TypeScript:从接口(interface)方法返回类的实例

javascript - 类型错误 : is not a function TypeScript

javascript - 在运行时使用控制台输入调试 typescript 应用程序

javascript - 防止 Router.Navigate 上的页面跳转

typescript - 在 typescript 中克隆一个类实例