0

I created this typescript file to show the problem:

enum E {
    one,
    two
}

console.log(E.one)
console.log(E.two)

let n: E = E.one
if (n === E.one) console.log("equal");
if (n === E.two) console.log("equal");

I get compile error from tsc on second if:

test.ts:11:5 - error TS2367: This condition will always return 'false' since the types 'E.one' and 'E.two' have no overlap.

I can't find out why it is happening. Am I doing something wrong?

0

1 Answer 1

3

This is intended behaviour (see this issue).

TypeScript's control flow analysis is smart enough to see that you just assigned E.one to n. There is now "invisible" type information associated with n which narrows down its type to E.one and will lead to the error in the if-statement because it knows that the condition will always evaluate to false.

If you want to avoid this behaviour, you can use the as operator which lets TypeScript conveniently forget the narrowed type information about n.

let n: E = E.one as E

if (n === E.one) console.log("equal");
if (n === E.two) console.log("equal");

Playground

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

1 Comment

It is a strange behavior and I commented on it in the pointed issue.

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.