Borislav Hadzhiev
Mon Feb 14 2022·2 min read
Photo by Cristina Gottardi
To use a switch statement with enums:
enum Sizes { Small, Medium, } function getSize(size: Sizes) { switch (size) { case Sizes.Small: console.log('small'); return 'S'; case Sizes.Medium: console.log('medium'); return 'M'; default: throw new Error(`Non-existent size in switch: ${size}`); } } console.log(getSize(Sizes.Small)); // 👉️ "S" console.log(getSize(Sizes.Medium)); // 👉️ "M"
We created a reusable function that takes an enum value as a parameter, switches on the enum value before returning something else.
If you have a numeric enum and you try to use a switch statement directly, you might get an error that "Type X is not compatible to type Y".
In this scenario, you can convert the enum value to a number when switching on it.
enum Sizes { Small, Medium, } switch (Number(Sizes.Small)) { case Sizes.Small: console.log('size is S'); break; case Sizes.Medium: console.log('size is M'); break; default: console.log(`non-existent size: ${Sizes.Small}`); break; }
Had we not converted the enum value to a number when switching on it, we would get an error that the two types are not compatible.
Make sure to always use the break
keyword to avoid a fallthrough switch, which
could run multiple code blocks.
If you're in a function, you will most likely be using return
instead of
break
.
If you are getting a similar error when working with string enums, you can convert the value to a string in the switch statement.
enum Sizes { Small = 'S', Medium = 'M', } switch (String(Sizes.Small)) { case Sizes.Small: console.log('size is S'); break; case Sizes.Medium: console.log('size is M'); break; default: console.log(`non-existent size: ${Sizes.Small}`); break; }
If you run the code from the example above, the size is S
message gets logged
to the console.