Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator === will always return 'false' since the types have no overlap

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]

like image 913
Ayush Agrawal Avatar asked Jan 23 '19 08:01

Ayush Agrawal


1 Answers

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.

like image 143
Dan F Avatar answered Oct 16 '22 14:10

Dan F