Typing useReducer Actions and State
You'll learn: How to create discriminated unions for reducer actions and type the reducer function for compile-time safety when dispatching updates.
Why Type Safety Matters for Reducers
When you use useReducer in React, you're managing state through actions. Without proper typing, you can dispatch invalid actions or access state properties that don't exist. TypeScript can prevent both categories of errors by making your actions into discriminated unions and constraining your reducer function.
Think of it like a vending machine: you insert specific coins (actions) with exact denominations (payloads), and the machine (reducer) knows exactly how to respond to each valid input. TypeScript ensures you can't insert a button or a paper clip.
Creating Discriminated Union Actions
Start by defining each action as an object type with a type property as the discriminant:
type Action =
| { type: 'increment' }
| { type: 'decrement' }
| { type: 'set'; payload: number }
| { type: 'reset' };
Each variant is a separate object type. TypeScript will narrow which properties exist based on the type field.
Typing the Reducer Function
Your reducer function receives the current state and an action, returning the next state:
interface State {
count: 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':
// TypeScript knows action.payload exists here
return { count: action.payload };
case 'reset':
return { count: 0 };
default:
return state;
}
}
TypeScript narrows the action type in each case branch, so action.payload is only accessible where it exists.
Using with useReducer Hook
Connect your typed reducer to React:
const [state, dispatch] = useReducer(reducer, { count: 0 });
// Type-safe dispatches
dispatch({ type: 'increment' }); // ✓ Valid
dispatch({ type: 'set', payload: 42 }); // ✓ Valid
// dispatch({ type: 'set' }); // ✗ Error: payload required
// dispatch({ type: 'invalid' }); // ✗ Error: invalid type
Autocomplete will suggest valid action types, and TypeScript prevents you from dispatching malformed actions.
Key Takeaway: Use discriminated unions for reducer actions with a type property as the discriminant, then type your reducer function to accept those actions—TypeScript will narrow action shapes in each branch and prevent invalid dispatches at compile time.