The issue here has to do with typescript's (numeric) literal types. When you do this assignment:
var editMode = EditMode.Edit
TypeScript evaluates the type as:
var editMode: 1 = EditMode.Edit
Now, when you compare a value that typescript knows must be 1
(EditMode.Edit
) to a value that it knows must be 0
(EditMode.View
), it sees all this as a type-safety violation. If the variable editMode
weren't an enum
, typescript would merely complain, but since it's an enum
, which doesn't really exist in javascript, typescript gets to control the transpilation in such a way that it actually throws an error.
So you have 2 options. So you can either coerce editMode
to be a number
or to be an EditMode
(i.e. any of the values EditMode
is permitted to be, not just the one assigned to editMode
the variable).
Personally, I prefer to coerce it to be an EditMode
, because it feels more type-safe.
To go the number route, you can do the following, which was previously mentioned:
switch(+editMode)
To go the EditMode
route (which I recommend), you can pass it to a function as was mentioned, but sometimes it's a little cleaner to not write a function. If that's the case here, then you can again coerce the type in the switch
statement:
switch(editMode as EditMode)
Do whichever you prefer, but I just like the clarity of explicitly saying "this variable is being treated as an EditMode
" as opposed to "this variable is supposed to actually be a number
, not an Enum
".