Skip to content
MacTokyo.
日本語

TypeScript Wiki

Cover every variant with switch

Give both versions of buttonColor the same input. Remove the secondary case to see which call can reach the end without returning a color.

Button variant

buttonColor({ label: "Save", variant: "secondary" })

ButtonProps
type ButtonProps = {
  label: string;
  variant: "primary" | "secondary" | "danger" | "ghost";
};

if

"gray"
function buttonColor(props: ButtonProps): string {
  if (props.variant === "danger") {
    return "red";
  }
  if (props.variant === "primary") {
    return "blue";
  }
  if (props.variant === "ghost") {
    return "gray";
  }
  if (props.variant === "secondary") {
    return "gray";
  }
}

TS2366 · All four inputs return colors, but TypeScript cannot prove these separate if statements cover every path.

switch

"gray"
function buttonColor(props: ButtonProps): string {
  switch (props.variant) {
    case "danger":
      return "red";
    case "primary":
      return "blue";
    case "ghost":
      return "gray";
    case "secondary":
      return "gray";
  }
}

Type check passed. Every member of the union has a case that returns a string.

How to read a case

switch reads props.variant. Each case is an entry point: a value of "ghost" enters at case "ghost". Its return ends the function, so it needs no break. TypeScript checks every possible input, even while you are trying just one.

Previous: branching on a variant