Sub topic 13
Typing reducers with discriminated unions
This chapter assumes you know how useReducer, actions, and reducers work, and that you have basic TypeScript experience with type aliases and unions. You will type a reducer so the compiler checks every action you dispatch.
Why type a reducer
In plain JavaScript, a typo such as dispatch({ type: 'incrmented' }) fails only at runtime, when the reducer reaches its default branch. A set action that forgets its value field produces NaN or undefined in state. TypeScript can catch both mistakes while you write the code.
The tool for this is a discriminated union. It is a union of object types that share one field, called the discriminant, whose type is a different string literal in each member. Here the discriminant is type.
Typing state and actions
Define the state shape, then one union member for each action:
type State = { count: number };
type Action =
| { type: 'incremented' }
| { type: 'decremented' }
| { type: 'set'; value: number };
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'incremented':
return { count: state.count + 1 };
case 'decremented':
return { count: state.count - 1 };
case 'set':
return { count: action.value };
}
}
// Usage inside a component:
// const [state, dispatch] = useReducer(reducer, { count: 0 });
// dispatch({ type: 'set', value: 5 });Inside case 'set', TypeScript narrows action to { type: 'set'; value: number }. That is why action.value is allowed there. In case 'incremented', reading action.value is a compile error because that member has no value field.
What the compiler checks for you
useReducer infers its types from the reducer, so you rarely write generics yourself. The dispatch function accepts only values that match Action.
| Call | Result |
|---|---|
| `dispatch({ type: 'set', value: 5 })` | Compiles |
| `dispatch({ type: 'set' })` | Error: `value` is missing |
| `dispatch({ type: 'incrmented' })` | Error: not a valid `type` |
| `dispatch({ type: 'incremented', value: 1 })` | Error: unknown field `value` |
The reducer declares its return type as State. If a case returns { count: 'x' } or { cnt: 1 }, the compiler rejects it.
Checking that every action is handled
The reducer above has no default branch. With strict enabled, TypeScript sees that the three cases cover every member of Action, so every path returns a State. Add a fourth member, { type: 'reset' }, and the function can now fall through without returning. The compiler reports that the function lacks an ending return statement. This warns you to handle the new action.
You can make this check explicit with the never type:
type State = { count: number };
type Action =
| { type: 'incremented' }
| { type: 'decremented' }
| { type: 'set'; value: number };
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'incremented':
return { count: state.count + 1 };
case 'decremented':
return { count: state.count - 1 };
case 'set':
return { count: action.value };
default: {
const unreachable: never = action;
throw Error('Unknown action: ' + JSON.stringify(unreachable));
}
}
}After all cases are handled, action has type never in the default branch. If you add a new action and forget its case, action is no longer never there, and the assignment fails to compile. You also keep a runtime error for callers that bypass the types.
Common errors
- Widened literals. Writing
const action = { type: 'incremented' }and then callingdispatch(action)fails, because TypeScript inferstype: string. Annotate the variable asAction, or write the object inside thedispatchcall. - Optional payloads. Avoid one
Actiontype withvalue?: number. Narrowing then proves nothing, andaction.valuemay beundefinedin every case. - Using
ifchains without a discriminant. Narrowing needs a literal-typed shared field. If members use different field names to tell them apart, the reducer loses the narrowing shown above. - Skipping
strict. Withoutstrict(or at leaststrictNullChecks), the missing-return check from the previous section does not run.
Exercise
You add { type: 'reset' } to the Action union, but the reducer's switch has no case 'reset'. The reducer ends with a default branch that assigns action to a variable of type never. What happens, and why?
Show answer
The code fails to compile. After the existing cases are removed from consideration, action in the default branch still has type { type: 'reset' }, which is not assignable to never. The error points you to the unhandled action. Adding case 'reset': return { count: 0 }; makes action never again and fixes it.
Exercise
Why is dispatch({ type: 'set' }) a compile error, while dispatch({ type: 'incremented' }) is not?
Show answer
dispatch accepts only values of type Action. The 'set' member requires a numeric value field, so an object without it matches no union member. The 'incremented' member has no payload field, so { type: 'incremented' } matches it exactly.