Sub topic 13
Typing reducers with discriminated unions
This chapter shows how to type a reducer in TypeScript so the compiler checks each action's payload, rejects invalid dispatch calls, and warns you when you forget to handle an action. It assumes you can write a reducer and call useReducer, and that you know basic TypeScript: type aliases, union types, and generics. You do not need to know discriminated unions yet.
The problem with untyped actions
In plain JavaScript, an action is any object with a type string. Nothing stops you from dispatching { type: 'set', valeu: 5 }, and you find the typo only when the UI shows undefined.
A first attempt at typing is often this:
type Action = { type: string; value?: number };This compiles almost everything, including mistakes. value is optional, so dispatch({ type: 'set' }) is allowed. Inside the reducer, action.value is number | undefined in every case, so you need checks or ! assertions. The type says nothing about which actions carry which data.
A discriminated union fixes this by describing each action as its own object type and joining them with |.
Discriminated unions
A discriminated union is a union of object types that share one property, the discriminant, whose type is a different literal in each member. For actions, the discriminant is type.
type State = { count: number };
type Action =
| { type: 'incremented' }
| { type: 'decremented' }
| { type: 'set'; value: number };Each member lists exactly the fields that action needs. incremented has no payload. set has a required value: number.
How narrowing works
When you check the discriminant, TypeScript narrows the union to the matching member. A switch on action.type does this in each case:
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':
// Here action is { type: 'set'; value: number }
return { count: action.value };
}
}In the 'set' case, action.value is a plain number. In the 'incremented' case, action.value is a compile error because that member has no value property.
Narrowing only works when the discriminant is a literal type. If you declare type: string, TypeScript cannot tell the members apart, and you are back to the untyped version.
Connecting the reducer to useReducer
useReducer infers the state and action types from the reducer function you pass in. If the reducer is annotated, you do not need explicit generics.
import { useReducer } from 'react';
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 };
}
}
export default function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'incremented' })}>+1</button>
<button onClick={() => dispatch({ type: 'set', value: 5 })}>Set to 5</button>
</>
);
}The compiler now checks every dispatch call:
dispatch({ type: 'set' })fails becausevalueis missing.dispatch({ type: 'set', value: '5' })fails becausevaluemust be a number.dispatch({ type: 'reset' })fails because'reset'is not in the union.state.coutfails becauseStatehas no such property.
The initial state { count: 0 } is also checked against State.
Annotating the reducer return type
Write : State on the reducer's return type. Without it, TypeScript infers the return type from the returned expressions. A case that returns the wrong shape then becomes part of the inferred type instead of an error, and the mismatch appears later at the useReducer call, which is harder to trace.
Exhaustiveness checking
The reducer above has no default case. TypeScript sees that the switch covers every member of Action, so no code path falls through and the function always returns a State.
Now add a member to the union:
type Action =
| { type: 'incremented' }
| { type: 'decremented' }
| { type: 'set'; value: number }
| { type: 'reset' };The reducer no longer handles every action. With strict enabled, the compiler reports that the function lacks an ending return statement and that its return type does not include undefined. You learn about the missing case at build time instead of from a bug report.
For a clearer message, and for a safety net at runtime, add a default case that uses never:
function assertNever(value: never): never {
throw new Error('Unhandled action: ' + JSON.stringify(value));
}
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 };
case 'reset':
return { count: 0 };
default:
return assertNever(action);
}
}After all four cases, action has the type never in the default branch, so passing it to assertNever compiles. If you remove the 'reset' case, action in the default branch is { type: 'reset' }, which is not assignable to never, and the compiler points at that line. At runtime, the function throws, which matches the throw Error('Unknown action: ...') convention from earlier chapters.
Typing a reducer with payloads
Real reducers carry more data. This todo reducer uses a named Todo type and an action for each operation.
export type Todo = { id: number; text: string; done: boolean };
export type TodoAction =
| { type: 'added'; id: number; text: string }
| { type: 'toggled'; id: number }
| { type: 'deleted'; id: number };
export function todosReducer(todos: Todo[], action: TodoAction): Todo[] {
switch (action.type) {
case 'added':
return [...todos, { id: action.id, text: action.text, done: false }];
case 'toggled':
return todos.map(t => (t.id === action.id ? { ...t, done: !t.done } : t));
case 'deleted':
return todos.filter(t => t.id !== action.id);
}
}Two details matter here. The object literal in the 'added' case is checked against Todo, so omitting done is an error. Also, because the State type is Todo[], the reducer cannot mutate by accident in a way the type system would miss. If you want the compiler to enforce immutability, declare the parameter as readonly Todo[] and the return type as readonly Todo[]. Then todos.push(...) fails to compile.
Modeling async state as a union
State can be a discriminated union too. The loading example from earlier chapters stores status, data, and error as three independent fields, so nothing prevents { status: 'loading', data: someOldData } from existing. A union describes only the valid combinations:
import { useEffect, useReducer } from 'react';
type FetchState<T> =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; error: string };
type FetchAction<T> =
| { type: 'fetch_started' }
| { type: 'fetch_succeeded'; data: T }
| { type: 'fetch_failed'; error: string };
function fetchReducer<T>(state: FetchState<T>, action: FetchAction<T>): FetchState<T> {
switch (action.type) {
case 'fetch_started':
return { status: 'loading' };
case 'fetch_succeeded':
return { status: 'success', data: action.data };
case 'fetch_failed':
return { status: 'error', error: action.error };
}
}
type User = { id: number; name: string };
export default function UserCard({ url }: { url: string }) {
const initial: FetchState<User> = { status: 'idle' };
const [state, dispatch] = useReducer(fetchReducer<User>, initial);
useEffect(() => {
let ignore = false;
dispatch({ type: 'fetch_started' });
fetch(url)
.then(res => {
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.json() as Promise<User>;
})
.then(data => {
if (!ignore) dispatch({ type: 'fetch_succeeded', data });
})
.catch((e: Error) => {
if (!ignore) dispatch({ type: 'fetch_failed', error: e.message });
});
return () => {
ignore = true;
};
}, [url]);
if (state.status === 'loading') return <p>Loading...</p>;
if (state.status === 'error') return <p>Error: {state.error}</p>;
if (state.status === 'success') return <p>{state.data.name}</p>;
return null;
}The reducer is generic, and fetchReducer<User> is an instantiation expression (TypeScript 4.7 and later) that fixes T to User. In the render code, state.data is only accessible after you check state.status === 'success', so the compiler stops you from reading data while loading. The res.json() as Promise<User> cast is a promise by you, not a check: the compiler does not validate the server's response.
Typing dispatch and context
The type of dispatch is Dispatch<Action>, which you import from React. You need it when you pass dispatch through context or as a prop.
import {
createContext,
useContext,
useReducer,
type Dispatch,
type ReactNode,
} from 'react';
type State = { count: number };
type Action = { type: 'incremented' } | { type: 'set'; value: number };
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'incremented':
return { count: state.count + 1 };
case 'set':
return { count: action.value };
}
}
const StateContext = createContext<State | null>(null);
const DispatchContext = createContext<Dispatch<Action> | null>(null);
export function CounterProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<StateContext.Provider value={state}>
<DispatchContext.Provider value={dispatch}>{children}</DispatchContext.Provider>
</StateContext.Provider>
);
}
export function useCounter(): State {
const value = useContext(StateContext);
if (value === null) throw new Error('useCounter must be used inside CounterProvider');
return value;
}
export function useCounterDispatch(): Dispatch<Action> {
const value = useContext(DispatchContext);
if (value === null) throw new Error('useCounterDispatch must be used inside CounterProvider');
return value;
}The contexts are typed as ... | null because createContext needs a default value before a provider exists. The custom hooks check for null once and return a non-null type, so components that call them never need their own null checks. Code outside a provider fails with a readable error.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| `type: string` in the action | No narrowing, every payload is optional | Use string literals such as `'set'` |
| One action type with optional fields | Invalid combinations compile | One union member per action |
| Omitting the reducer return type | Wrong return shapes surface at the wrong place | Annotate the return type |
| Catch-all `default: return state` | Missing cases go unnoticed | Use `assertNever` or no default |
| Building an action in a variable | `type` widens to `string` | Annotate it as `Action` or use `as const` |
The fourth row deserves an example. This fails to compile:
const action = { type: 'set', value: 5 };
dispatch(action); // Error: type 'string' is not assignable to the unionThe object's type property is widened to string when assigned to a mutable object. Either annotate the variable (const action: Action = ...) or write the object inline in the dispatch call, where the expected type is known.
Exercise
A reducer handles { type: 'added'; text: string } and { type: 'cleared' }. A teammate adds { type: 'renamed'; id: number; text: string } to the Action union but forgets to update the reducer. The reducer has a default: return assertNever(action) branch. What happens at compile time, and why?
Show answer
The compiler reports an error on the assertNever(action) line. After the two handled cases, action in the default branch is still { type: 'renamed'; id: number; text: string }, which is not assignable to never. The error disappears once a 'renamed' case is added and narrows the union fully.
Exercise
Rewrite type Action = { type: 'set' | 'reset'; value?: number } as a discriminated union so that dispatch({ type: 'set' }) is a compile error and reset takes no value.
Show answer
type Action = { type: 'set'; value: number } | { type: 'reset' };