React·Advanced·Scenario based·1 min read
How do discriminated unions improve reducer design?
Short interview answer
A literal type field narrows each action to its valid payload, and a union can model mutually exclusive states. Exhaustive checking catches forgotten transitions when a new event or state is added.
Example
type Action = | { type: 'submitted' } | { type: 'succeeded'; order: Order } | { type: 'failed'; message: string };
function reducer(state: State, action: Action): State { switch (action.type) { case 'succeeded': return { status: 'success', order: action.order }; case 'failed': return { status: 'error', message: action.message }; // ... }}Key takeaway
Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.