Sub topic 11
Typing useReducer with action unions
This chapter assumes you know how useReducer works in plain React and that you can read TypeScript unions and switch statements. You will type the state, describe every action as a union, and let the compiler check each case.
Why a union of actions
A reducer is a function that takes the current state and an action, and returns the next state. In JavaScript, an action is an object with a type string, and nothing stops you from dispatching { type: "incremant" }.
With TypeScript you describe the allowed actions as a union of object types. Each member has a literal type property, called the discriminant. This is the same idea as the discriminated unions for props in the previous chapter.
The state, the actions, and the reducer
import { useReducer } from "react";
type State = { count: number };
type Action =
| { type: "increment" }
| { type: "decrement" }
| { type: "set"; value: number };
function reducer(state: State, action: Action): State {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
case "set":
return { count: action.value };
}
}
export function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<button onClick={() => dispatch({ type: "increment" })}>
{state.count}
</button>
);
}Three things are worth noticing.
- You never write type arguments for
useReducer. TypeScript reads them from thereducersignature, sostateisStateanddispatchaccepts onlyAction. - Inside
case "set", TypeScript narrowsactionto{ type: "set"; value: number }. That is whyaction.valueis allowed there and not in the other cases. - The return type
Stateis explicit. If a case returns the wrong shape, the error appears in the reducer instead of at some distant use of the state.
flowchart TDWhat the compiler now catches
Each of these calls is a compile-time error:
dispatch({ type: "reset" }), because"reset"is not in the union.dispatch({ type: "set" }), becausevalueis missing.dispatch({ type: "increment", value: 3 }), because theincrementmember has novalue.
Exhaustive checking
With strict on, the reducer above compiles because every member of Action has a case, so TypeScript knows the function always returns. Add { type: "reset" } to the union and the function now has a code path with no return, which is an error. The compiler tells you which reducer to update.
You can make this explicit with a helper that only accepts never:
function assertNever(value: never): never {
throw new Error(`Unhandled action: ${JSON.stringify(value)}`);
}Call assertNever(action) in a default: branch. After all cases are handled, action has type never, so the call compiles. If a case is missing, action still has a real type and the call fails.
Payload actions and common mistakes
Keep the discriminant a literal type. If you write type: string, narrowing stops working and every action.value access fails.
Do not mutate state inside the reducer. TypeScript will not stop you. To catch this at compile time, you can mark fields readonly in State.
If your reducer needs the action types elsewhere, for example in a helper that builds actions, export Action and reuse it. You can also pull one member out with Extract<Action, { type: "set" }>.
Exercise
You add { type: "reset" } to the Action union but forget to add a case to the reducer. The reducer has the return type State and strict is on. What happens, and why?
Show answer
The compiler reports an error that the function lacks an ending return statement and its return type does not include undefined. The switch no longer covers every member of the union, so one path returns nothing. Adding a case "reset" (or a default that calls assertNever) fixes it.