What is a discriminated union, and what role does the common 'discriminant' property play?
Short answer
A discriminated union is a union of object types that all share a common literal-typed property (the discriminant, often called 'kind' or 'type').
Advertisement
AModel answer
A discriminated union is a union of object types that all share a common literal-typed property (the discriminant, often called 'kind' or 'type'). Checking that property's value in an if or switch lets TypeScript automatically narrow the whole object to the matching specific type.
type Circle = { kind: 'circle'; radius: number };
type Square = { kind: 'square'; side: number };
type Shape = Circle | Square;Real-world example
Modeling different states of an async request (loading, success, error) as a discriminated union.
Likely follow-ups
- What happens if two variants accidentally share the same discriminant value?
Related topics