How would you write a reducer function (Redux-style) that exhaustively handles every action type in a discriminated union of actions?
Short answer
Type the reducer's action parameter as a discriminated union of all possible Action types (each with a unique 'type' discriminant), switch on action.type, and add a default case using the assertNever(action) pattern — this guarantees the compiler flags any new action type added…
Advertisement
AModel answer
Type the reducer's action parameter as a discriminated union of all possible Action types (each with a unique 'type' discriminant), switch on action.type, and add a default case using the assertNever(action) pattern — this guarantees the compiler flags any new action type added later that isn't yet handled in the reducer.
type Action =
| { type: 'increment'; amount: number }
| { type: 'decrement'; amount: number }
| { type: 'reset' };
function reducer(state: number, action: Action): number {
switch (action.type) {
case 'increment': return state + action.amount;
case 'decrement': return state - action.amount;
case 'reset': return 0;
default: return assertNever(action);
}
}Real-world example
Building a type-safe Redux or useReducer reducer where forgetting to handle a new action type is caught at compile time, not at runtime.
Likely follow-ups
- How does this pattern scale when action creators are also generated from the same discriminated union?
Related topics