Last updated: Feb 26, 2024
Reading timeยท2 min
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: // ๐๏ธ this runs 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 use 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.
If you get the Conversion of type 'X' to type 'Y' may be a mistake in TS error, click on the link and follow the instructions.
If you need to check if a value exists in an enum, click on the following article.
You can learn more about the related topics by checking out the following tutorials: