Skip to content

Discriminated Union

Medium — good to knowGeneral Dev

ELI5 — The Vibe Check

A discriminated union is like a box that could contain a cat, a dog, or a fish — but it has a label on the outside telling you which one. TypeScript reads the label and knows exactly what's inside without opening it.

Real Talk

A TypeScript pattern where a union type has a common literal property (the discriminant) that TypeScript can use for type narrowing. Each variant of the union has a unique value for this property, enabling exhaustive pattern matching in switch statements and conditionals.

Show Me The Code

type Shape =
  | { kind: 'circle'; radius: number }
  | { kind: 'rectangle'; width: number; height: number }
  | { kind: 'triangle'; base: number; height: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case 'circle': return Math.PI * shape.radius ** 2;
    case 'rectangle': return shape.width * shape.height;
    case 'triangle': return (shape.base * shape.height) / 2;
  }
}

When You'll Hear This

"Model your API responses as discriminated unions — success and error should be different shapes." / "The 'kind' field as a discriminant lets TypeScript narrow perfectly in switch statements."

Made with passive-aggressive love by manoga.digital. Powered by Claude.