In TypeScript, I want to compare two variables containing enum values. Here's my minimal code example:
enum E { A, B } let e1: E = E.A let e2: E = E.B if (e1 === e2) { console.log("equal") }
When compiling with tsc
(v 2.0.3) I get the following error:
TS2365: Operator '===' cannot be applied to types 'E.A' and 'E.B'.
Same with ==
, !==
and !=
. I tried adding the const
keyword but that seems to have no effect. The TypeScript spec says the following:
4.19.3 The <, >, <=, >=, ==, !=, ===, and !== operators
These operators require one or both of the operand types to be assignable to the other. The result is always of the Boolean primitive type.
Which (I think) explains the error. But how can I get round it?
Side note
I'm using the Atom editor with atom-typescript, and I don't get any errors/warnings in my editor. But when I run tsc
in the same directory I get the error above. I thought they were supposed to use the same tsconfig.json
file, but apparently that's not the case.
To compare enums, use dot notation to get the value for a specific enum property and compare it to another value, e.g. if (MyEnum. Small < 2) {} . The values for numeric enums, without provided initial value, are auto-incrementing integers, starting at 0 .
We can compare enum variables using the following ways. Using Enum. compareTo() method. compareTo() method compares this enum with the specified object for order.
There are two ways for making comparison of enum members : equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.
By the way unlike comparing String in Java, you can use both == and equals() method to compare Enum, they will produce same result because equals() method of Java. lang. Enum internally uses == to compare enum in Java.
Well I think I found something that works:
if (e1.valueOf() === e2.valueOf()) { console.log("equal") }
But I'm a bit surprised that this isn't mentioned anywhere in the documentation.
There is another way: if you don't want generated javascript code to be affected in any way, you can use type cast:
let e1: E = E.A let e2: E = E.B if (e1 as E === e2 as E) { console.log("equal") }
In general, this is caused by control-flow based type inference. With current typescript implementation, it's turned off whenever function call is involved, so you can also do this:
let id = a => a let e1: E = id(E.A) let e2: E = id(E.B) if (e1 === e2) { console.log('equal'); }
The weird thing is, there is still no error if the id
function is declared to return precisely the same type as its agument:
function id<T>(t: T): T { return t; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With