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?
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");