"have no overlap" error while comparing enum values in TypeScript

Viewed 1642

I'm trying to learn TypeScript and had been following online tutorial examples for enum support in TypeScript. For this below snippet:

enum daysoftheweek{
    SUN, MON, TUE, WED, THU, FRI, SAT
}

let day:daysoftheweek ;

day = daysoftheweek.FRI; //line 7

if (day === daysoftheweek.MON){
    console.log("got to go to work early");
}else{
    console.log("I may go late");
}

...I'm getting this error at compile time and I don't understand why:

TS2367: This condition will always return 'false' since the types 'daysoftheweek.FRI' and 'daysoftheweek.MON' have no overlap.

If I modify line 7 to this, the error goes off: day = daysoftheweek.MON;

Can somebody please explain why compilation is throwing that error?
(I followed other threads on this "have no overlap" error , but couldn't understand the reason for this particular snippet's problem)

3 Answers

There is no logic applied that could affect the value of the day variable -- the complier can plainly see that it will always be daysoftheweek.FRI. The error is telling you that it will never equal daysoftheweek.MON so the if statement has no purpose.

Note that this error can also occur if you have multiple enums with the same values. For example if you have Enum1.OTHER = "other" and Enum2.OTHER = "other" and you try to compare a value that should be of type Enum1 with Enum1.OTHER, you'd think it would work fine. But no, Typescript gets confused and doesn't know if "other" is for Enum1 or Enum2. The way to get around this is to always use it like this:

let action:Enum1 = whatever;
if (action == (Enum1.OTHER as Enum1)) {
    // do something
} else if (action == (Enum1.SOMETHING_ELSE as Enum1)) {
    // do something else
}

Took some random guessing on my part to find the issue and make this error go away.

It can happen if you repeat the Enum conditional.

Related