Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript enum switch not working

i have the following enum

enum EditMode {     View = 0,     Edit = 1,     Delete = 2 } 

Let's assume i have a variable of the enum type

var editMode = EditMode.Edit; 

Why does the following code not work (goes straight to default)?

switch (editMode) {     case EditMode.Delete:         ...         break;     case EditMode.Edit:         ...         break;     default:         ...         break;     } 
like image 475
Mantzas Avatar asked Jan 02 '15 19:01

Mantzas


People also ask

Can I use enum in switch?

We can use also use Enum keyword with Switch statement. We can use Enum in Switch case statement in Java like int primitive. Below are some examples to show working of Enum with Switch statement.

What is Fallthrough case in switch TypeScript?

Code Inspection: Fallthrough in 'switch' statementReports a switch statement where control can proceed from a branch to the next one. Such "fall-through" often indicates an error, for example, a missing break or return .

How enum work in TypeScript?

Enums are a feature added to JavaScript in TypeScript which makes it easier to handle named sets of constants. By default an enum is number based, starting at zero, and each option is assigned an increment by one. This is useful when the value is not important.

Should enums be capitalized TypeScript?

Use uppercase letters for your enums - they are global constants which have usable values. They are more than just types, which use usually like Foo or TFoo . The keys on an enum tend to be titlecase.


2 Answers

I also had this problem. Easy way to get around it: add a + sign before your variable in the switch, i.e.

switch (+editMode) {     case EditMode.Delete:         ...         break;     case EditMode.Edit:         ...         break;     default:         ...         break;     } 
like image 142
Shaul Behr Avatar answered Sep 20 '22 22:09

Shaul Behr


i have found why i does happen. somewhere in the code there is a activation function (i am using durandal) which passes this enum as a string (the function has the parameter marked as a enum but still it is a string). this is why my switch statement fails. i simply converted the value to a number and now everything works as expected. thanks anyways

like image 39
Mantzas Avatar answered Sep 23 '22 22:09

Mantzas