Optimize

Discriminated union

A discriminated union is a union type whose variants share a literal-typed property (the discriminant) that uniquely identifies each variant, typically named 'type', 'kind', or 'tag'. The discriminant lets TypeScript narrow the union via a switch or if-check, with exhaustive case handling enforced by the type system.

Updated

Discriminated unions are TypeScript's idiomatic way to model alternatives: a Result that's either Ok or Err, a Shape that's a Circle or Square or Triangle, a NetworkState that's Idle or Loading or Loaded or Error. The pattern produces exhaustiveness checking: forget a case in a switch, and either the return type widens or the never-check fires. The discipline is to use the same discriminant name across the codebase (Stride convention: 'kind'). The pattern is the antidote to the 'object with optional fields where exactly one is set' anti-pattern that produces undefined-checks throughout the consuming code.

See the term at work

Stride keeps stories, architecture decisions, tests and delivery data in one workspace, where the terms in this glossary are things you can open.