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.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe 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.dataexists. - Use string literal tags, not a boolean:
isLoading: booleanplus optional data and error allows impossible states (loading AND error) and can't express idle. - Add
neverexhaustiveness 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
- How would you type the state of a data fetch in a component?
- Why is a boolean isLoading weaker than a status union?
- How do you make the compiler force handling of a new state?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.