Russley

Blog

Exhaustive Switch Case

Using never to assert things.
TypeScript
Created about 2 months ago

Foo

Non-exhaustive switch case

TypeScript

enum Color {
  Red,
  Green,
  Blue,
}

function getColorName(color: Color): string {
  switch (color) {
    case Color.Red:
      return "Red";
    case Color.Green:
      return "Green";
    case Color.Blue:
      return "Blue";
  }
}
Compiling...
TypeScript

function unhandledState(state: never, msg: string): never {
  throw new Error(`Unhandled state: ${msg}`);
}

unhandledState(1, "Oops");
unhandledState(1, "Oops");
Compiling...