Zum Hauptinhalt springen

Build a discriminated-union renderer

Use a discriminated union and switch statement to render state-specific data safely.

typescript-basics5 min read

step trail before-after exhaustiveness callout A subscription banner currently uses booleans and optional fields that can conflict. Discriminated union: one kind field controls valid data and render behavior Adding more optional fields looks flexible, but it pushes uncertainty into every render branch. Name exclusive cases Define pending, paid, and failed as separate alternatives. If only one can be true, model them as alternatives rather than independent flags. Attach valid data paid carries receiptId; failed carries reason; pending carries no receipt or reason. Case-specific fields remove optional-property guessing. Switch on the discriminant Render with switch (state.kind) and read fields only inside…

Read the full lesson

Sign up free: one personalized lesson every day, matched to your role and goals.

← Back to library

Kontakt aufnehmen