7

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)

0

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I understand now. I think I should not have expected a Java-like similarity, since this snippet is perfectly compile-valid for Java. Typescript is smarter :)
4

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.

Comments

2

It can happen if you repeat the Enum conditional.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.