Here is a snippet of code I am working with:
class A {
constructor(private num: number = 1) {
}
private changeNum() {
this.num = Math.random();
}
private fn() {
if(this.num == 1) {
this.changeNum();
if(this.num == 0.5) {
// do stuff
}
}
}
}
This code defines a class 'A' with a property num
and a method changeNum
to modify that number.
There is also a function fn
which checks if num
is equal to 1, then changes it using changeNum
, and checks it again.
The issue arises when TypeScript does not recognize that num
has been modified through the changeNum
method, resulting in the error message:
This condition will always return 'false' since the types '1' and '0.5' have no overlap.
Is there a way to make TypeScript understand that num
was altered by changeNum
?
EDIT: I discovered that changing if(this.num == 0.5)
to if(this.num == Number(0.5))
allows the program to compile correctly, but this doesn't seem like an optimal solution!