Skip to content
MacTokyo.
日本語

TypeScript Wiki

Same gray. Which if returned it?

buttonColor checks the button’s variant from top to bottom and returns a color at the first match. Switch from ghost to secondary: the button stays gray, but a different line returns it.

Button variant
What you sent
What buttonColor returned
"gray"

buttonColor.ts

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

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";
  }
}

From my November 27 notebook

I first compared variant with "red". The input is "danger"; "red" is the output. Each pair of braces encloses one if, like a frame in Figma. If the first three checks fail, only secondary is left.

Why does TypeScript flag string when all four buttons work?

The return annotation promises a string on every call. With strictNullChecks on, TypeScript cannot prove that this sequence of if statements always returns before the end (TS2366). A final return "gray" would also catch any newly added variant and quietly color it gray.

Previous: union types with AvatarProps Next: exhaustive switches