typescript switch statement with enums

2020-03-17

 | 

~1 min read

 | 

199 words

We use Enums a lot in our Typescript code to make sure that we’re using a value that we expect.

One way that we use the Enum is as the basis of a switch statement.

Instead of:

type Fruit = "Apple" | "Orange" | "Kiwi"

function getFruit(prop: Fruit) {
  switch (prop) {
    case "Apple":
      return () => <AppleComponent />
    case "Orange":
      return () => <AppleComponent />
    case "Kiwi":
      return () => <AppleComponent />
    default:
      throw Error(`Unknown fruit of type --> ${prop}`)
  }
}

With an Enum, it can be refactored to be more explicit as follows:

enum Fruit {
  Apple = "Apple",
  Orange = "Orange",
  Kiwi = "Kiwi",
}

function getFruit(prop: Fruit) {
  switch (prop) {
    case Fruit.Apple:
      return () => <AppleComponent />
    case Fruit.Orange:
      return () => <AppleComponent />
    case Fruit.Kiwi:
      return () => <AppleComponent />
    default:
      throw Error(`Unknown fruit of type --> ${prop}`)
  }
}

While Typescript provided type safety in the first iteration because of the type Fruit, by switching to an Enum the dependency is more explicit and can now provide hints through intellisense.

Related: Using the Default Enum as a Fallback

Resources



Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!