🏷️

TypeScript Discriminated Unions

Verified

by Community

Shows how to use discriminated unions in TypeScript for type-safe state modeling, action handling, and pattern matching. Covers the discriminant property pattern, exhaustive checks, and common use cases in React and Redux.

typescriptunionsdiscriminatedpattern-matchingstate

TypeScript Discriminated Unions

Model complex state and actions with discriminated unions for exhaustive type checking.

Usage

Describe your state modeling needs and get discriminated union patterns.

Examples

  • "Model API response states: loading, success, error"
  • "Create a type-safe action system for my reducer"
  • "How do I ensure exhaustive handling of union variants?"

Guidelines

  • Use a common literal property as the discriminant
  • Show exhaustive checks with never type or switch statements
  • Cover narrowing behavior in if/switch blocks
  • Include patterns for React state and Redux actions
  • Explain when to use discriminated unions vs other approaches