discriminated union
A type made of several object shapes that share one literal field, such as status or type, whose value tells them apart.
In more detail
When code checks that field in an if or switch, languages such as TypeScript narrow the value to the matching shape, so they know data exists only in the success case. It lets the compiler reject impossible states and unhandled cases.
Example
type State = { status: "idle" } | { status: "success"; data: string };Related terms
- TypeScript — JavaScript with added type annotations, checked by a compiler before the code runs.
- state machine — A model in which something is always in exactly one named state, such as idle, loading, success or error, and only defined events move it to another.
- reducer action — A plain object describing something that happened, usually with a type string and optional payload data, sent to a reducer through dispatch.
- union type — A type that allows one of several listed types or values, written with a vertical bar, such as int | None in Python or "small" | "large" in TypeScript.
- literal type — A type that allows exactly one value, such as the string "GET", the number 404 or true.
- switch statement — A statement that compares one value against a list of cases and runs the matching branch, with a default for everything else.
- exhaustiveness checking — Having the compiler prove that code handles every possible member of a union, so a newly added member causes a compile error.
- make illegal states unrepresentable — A design rule: shape your types so that invalid combinations, such as loading and error at once, cannot even be written.
Taught in
- Complex State with useReducer: State Machines And Action Types — React 19 & Modern Component Architecture
- never: The Bottom Type And Exhaustive Switch Checking — Production TypeScript
- Union Types, Intersections And Property Conflicts — Production TypeScript
- Discriminated Unions: Tagged Variants And Pattern Matching — Production TypeScript
- Tuples: Fixed Length, Labeled Elements And Variadic Tuples — Production TypeScript
- The in Operator And Instanceof Narrowing — Production TypeScript
- Exhaustive Narrowing With never In Production Handlers — Production TypeScript
- The Spine Artifact: Generating Typed Models From OpenAPI — Production TypeScript