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
and:
- Replace the placeholder
ApiStatewith a discriminated union onstatus. 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
- Replace the placeholder
PaymentMethodwith a discriminated union ontype. Valid variants (each exclusive):- credit card β
last4andexpirystrings - PayPal β
emailstring - bank β
accountNumberstring
- credit card β
- Remove the
@ts-expect-errorcomments once the unions are correct so theneverexhaustiveness checks type-check - Export
renderStateanddescribePaymentby name (their bodies are already written)
Completion criteria
- Named exports:
renderState,describePayment renderState/describePaymentkeep 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


