Reputation: 3230
I have a simple example on setting Union types inside a class.
class Foo {
constructor() {}
progress: number | string = 0;
bar() {
this.progress = this.progress + 5;
}
}
I expected to increment by 5 but instead I recieve a ts(2365) error.
Operator '+' cannot be applied to types 'string | number' and '5'.ts(2365)
I thought this would work because if I set this up outside of a class like this code below.
let progress: number | string = 0;
progress = progress + 5;
There are no errors.
Ultimately what I'm trying to do to is to set a variable inside a class declaration that accepts a number from setInterval
, so I'm trying to set the variable to the union types of number and NodeJS.Timer
since setInterval
returns 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);
}
}
I know I can simply assign <any>
to solve this issue this.interval = <any>setInterval( ()=>{} )
, but I wanted to see if I could try Union types.
Last thing that's not related to this issue, setting <number>
to setInterval
shows a warning 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)
Upvotes: 2
Views: 1456
Reputation: 2317
In bar function you can't be sure that your value now is a number. You can add additional check to make it work
class Foo {
constructor() {}
progress: number | string = 0;
bar() {
if (typeof this.progress === 'number')
this.progress = this.progress + 5;
}
}
In case of
let progress: number | string = 0;
progress = progress + 5;
value is definitely a number (it was assigned 1 line above)
Upvotes: 1