How to use a Switch statement with Enums in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 14, 2022

banner

Photo from Unsplash

Use a Switch statement with Enums in TypeScript #

To use a switch statement with enums:

  1. Create a reusable function that takes an enum value as a parameter.
  2. Use a switch statement and switch on the provided value.
  3. Return a specific value from each branch.
index.ts
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.

The default case is a matter of implementation. In the example, we throw an error to indicate that an unexpected state has occurred - the passed in value is not present in the enum.

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.

index.ts
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.

index.ts
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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.