Discriminated Union
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."
Related Terms
Pattern Matching
Pattern matching is like a super-powered switch statement that can look inside data structures and pull out the parts you need.
Sum Type
A sum type is 'this thing is EITHER a cat OR a dog OR a fish — pick one.' It's like a multiple choice question for types.
Type Narrowing
Type narrowing is TypeScript being a detective.
TypeScript
TypeScript is JavaScript with a strict parent watching over it.