Discriminated Unions

Discriminated Unions
πŸ‘¨β€πŸ’Ό Discriminated unions (also called "tagged unions" or "algebraic data types") are a pattern where each type in a union has a common "discriminant" property with a literal type value.
type Circle = { kind: 'circle'; radius: number }
type Rectangle = { kind: 'rectangle'; width: number; height: number }
type Shape = Circle | Rectangle
The kind property lets TypeScript narrow the type automatically. This is how you make invalid states unrepresentableβ€”the type system ensures you can only create valid combinations.
🐨 Open
index.ts
and:
  1. Replace the placeholder ApiState with a discriminated union on status. Valid variants (each exclusive β€” a loading state must not require success or error fields, and so on):
    • loading β€” only the loading discriminant
    • success β€” string-array data
    • error β€” string error
  2. Replace the placeholder PaymentMethod with a discriminated union on type. Valid variants (each exclusive):
    • credit card β€” last4 and expiry strings
    • PayPal β€” email string
    • bank β€” accountNumber string
  3. Remove the @ts-expect-error comments once the unions are correct so the never exhaustiveness checks type-check
  4. Export renderState and describePayment by name (their bodies are already written)

Completion criteria

  • Named exports: renderState, describePayment
  • renderState / describePayment keep working for each variant using the return strings already in the starter switch cases
  • Invalid mixed shapes (for example success fields on a loading state) are not representable

Please set the playground first

Loading "Discriminated Unions"
Loading "Discriminated Unions"