I have this code
enum Example {
First = "First",
Second = "Second"
}
let a = [1, 2];
let newStatus: Example = Example.First;
a.forEach(i => {
newStatus = Example.Second;
});
if (newStatus === Example.Second) {
// do something
}
Expected: No errors
Actual: Error: [ts] This condition will always return 'false' since the types 'Example.First' and 'Example.Second' have no overlap. [2367]
As per the comment by @titian-cernicova-dragomir and the answer on Why boolean becomes true? you can put a casting operator in to force the compiler to treat the enum as the enum, not just the last value of the enum it thought it was assigned.
So, in your case, you can change line 8 to
let newStatus: Example = Example.First as Example;
Or, if that doesn't fix it, you can change the comparison itself
if (newStatus === (Example.Second as Example)) {
// do something
}
I prefer to change the comparison as it is the line that the compiler is barfing over, but it entirely depends on how many comparisons you have vs how many assignments you have and which feels more understandable to you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With