Skip to the page

How TypeScript thinks · mid

Discriminated unions for real UI states

Model states that cannot happen together as a union of objects with a shared literal tag (status: 'idle' | 'loading' | 'success' | 'error'), so impossible combinations cannot be written and each state carries exactly its own data.

The notes

What you must know

  • A discriminated union has a common literal property (the tag): { status: 'success'; data: User[] } | { status: 'error'; error: string } | { status: 'loading' }.
  • Checking the tag narrows the whole object: inside if (s.status === 'success'), s.data exists.
  • Use string literal tags, not a boolean: isLoading: boolean plus optional data and error allows impossible states (loading AND error) and can't express idle.
  • Add never exhaustiveness so a new state forces every switch to handle it.
  • This is how reducers, API results ({ ok: true, value } | { ok: false, error }) and React Query style states are typed well.

The red pen

Common traps: mistake → fix

  • Mistake: "a boolean flag is enough"

    Fix: { loading: boolean; data?: T; error?: string } allows 8 combinations, most impossible; a tagged union allows exactly the valid ones.

  • Mistake: "optional fields are fine"

    Fix: they force ! or extra checks everywhere because the compiler can't know data exists.

Easy to hard

Questions interviewers ask, easy to hard

  1. How would you type the state of a data fetch in a component?
  2. Why is a boolean isLoading weaker than a status union?
  3. How do you make the compiler force handling of a new state?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview