How to Type a Reducer With Discriminated Unions
Model reducer actions as a discriminated union in TypeScript 6, get exhaustive checking with never, and build typed action creators that cannot drift.

A reducer is a function from a state and an action to a new state, and it is one of the best places to use a discriminated union. Each action has a type field that names it, and the payload depends on the name. If you type the actions as one loose object with optional fields, every branch has to guess which fields are present. If you type them as a union that is discriminated by type, the compiler narrows the action inside each branch and tells you when you forget a case. This post shows how to type a reducer with discriminated unions in TypeScript 6.x. The same code works in the native TypeScript 7 compiler, and with any library that follows the reducer shape, including React's useReducer. The language feature is described in the narrowing chapter of the handbook.
The problem with a loose action type
Here is the version that most projects start with.
interface Action {
type: string;
payload?: unknown;
}
interface State {
items: string[];
loading: boolean;
}
function reducer(state: State, action: Action): State {
switch (action.type) {
case "add":
return { ...state, items: [...state.items, action.payload as string] };
case "clear":
return { ...state, items: [] };
default:
return state;
}
}It compiles, and it is fragile. The as string cast hides a promise the compiler cannot check. A typo such as "claer" in a dispatch is accepted, because type is any string. A new action type added later is silently ignored by the default branch.
A discriminated union of actions
A discriminated union is a union of object types that share a property with literal types, called the discriminant. Each member has a different literal, and the other fields depend on it.
export type Action =
| { type: "add"; item: string }
| { type: "remove"; index: number }
| { type: "setLoading"; loading: boolean }
| { type: "clear" };
export interface State {
items: string[];
loading: boolean;
}
export const initialState: State = { items: [], loading: false };Each action carries exactly the data it needs, under a name that says what it is. There is no generic payload that must be cast.
The reducer
Switching on action.type narrows the action in each branch. Inside case "add", action is { type: "add"; item: string }, so action.item is a string with no cast.
import type { Action, State } from "./actions.ts";
import { initialState } from "./actions.ts";
export function reducer(state: State, action: Action): State {
switch (action.type) {
case "add":
return { ...state, items: [...state.items, action.item] };
case "remove":
return {
...state,
items: state.items.filter((_, i) => i !== action.index),
};
case "setLoading":
return { ...state, loading: action.loading };
case "clear":
return { ...state, items: [] };
}
}
let state = initialState;
state = reducer(state, { type: "add", item: "milk" });
state = reducer(state, { type: "add", item: "eggs" });
state = reducer(state, { type: "remove", index: 0 });
console.log(state);{ items: [ 'eggs' ], loading: false }There is no default branch, and none is needed. The function has a return type of State, and every member of the union is handled, so the compiler knows the function returns on every path. If you add a new action to the union and forget the case, the function can now fall through without returning, and the compiler reports it.
reducer.ts(5,59): error TS2366: Function lacks ending return statement and return type does not include 'undefined'.That error is the safety net. It means the new action was added to the type but not handled.
Exhaustiveness with never
The fall through error depends on the function's return type. A more explicit approach assigns the leftover action to a never variable in a default branch. If any member is unhandled, it is not never, and the assignment fails.
import type { Action, State } from "./actions.ts";
function assertNever(value: never): never {
throw new Error(`Unhandled action: ${JSON.stringify(value)}`);
}
export function reducer(state: State, action: Action): State {
switch (action.type) {
case "add":
return { ...state, items: [...state.items, action.item] };
case "remove":
return {
...state,
items: state.items.filter((_, i) => i !== action.index),
};
case "setLoading":
return { ...state, loading: action.loading };
case "clear":
return { ...state, items: [] };
default:
return assertNever(action);
}
}After all four cases, action in the default branch has the type never, so passing it to assertNever compiles. If someone adds a fifth action and no case, action has that member's type there, and the call is an error that names the missing action. The function also throws at run time if an unexpected value arrives, which can happen when data crosses a boundary and the types are wrong. That second property is why many teams prefer this form over relying on the return type alone.
Typed action creators
Hand written action objects are easy to get wrong in one place and repeat everywhere. Small creator functions keep the shape in one place, and their return types are derived from the union.
import type { Action } from "./actions.ts";
export const add = (item: string): Action => ({ type: "add", item });
export const remove = (index: number): Action => ({ type: "remove", index });
export const setLoading = (loading: boolean): Action => ({
type: "setLoading",
loading,
});
export const clear = (): Action => ({ type: "clear" });
console.log(add("tea"), clear());{ type: 'add', item: 'tea' } { type: 'clear' }Returning Action is accurate but loses the specific member, which matters little for dispatch. If you want the narrow type, use Extract<Action, { type: "add" }> as the return type, which picks that member out of the union.
Deriving the action type from the creators
The reverse direction also works, and it removes one declaration. Define the creators first and compute the union from their return types.
export const add = (item: string) => ({ type: "add", item }) as const;
export const remove = (index: number) => ({ type: "remove", index }) as const;
export const clear = () => ({ type: "clear" }) as const;
export type Action =
| ReturnType<typeof add>
| ReturnType<typeof remove>
| ReturnType<typeof clear>;
const a: Action = remove(2);
console.log(a);{ type: 'remove', index: 2 }The as const keeps type as a literal. Without it, the type would widen to string, and the union would no longer discriminate. The union lists each creator once, which is the one place you must edit when you add an action. Whether you prefer writing the union first or the creators first is a matter of taste. The union first reads as a specification, and the creators first has less repetition.
Using it with React
The same types plug into useReducer.
import { useReducer } from "react";
import { initialState, type Action, type State } from "./actions.ts";
import { reducer } from "./exhaustive.ts";
export function List() {
const [state, dispatch] = useReducer(reducer, initialState);
const send = (action: Action) => dispatch(action);
return (
<button onClick={() => send({ type: "add", item: "bread" })}>
{state.items.length}
</button>
);
}dispatch is typed as taking an Action, so dispatch({ type: "add" }) fails because item is missing, and dispatch({ type: "nope" }) fails because the literal is not in the union.
Keeping state transitions honest
Types describe the shape of an action, and they do not describe which actions make sense in which state. A reducer for a form might have submit only valid while the state is editing, and retry only valid after a failure. A flat state with several booleans lets any action run at any time and relies on discipline. A discriminated union can model the state as well, so impossible combinations cannot be written.
type State =
| { status: "idle" }
| { status: "loading"; startedAt: number }
| { status: "failed"; message: string }
| { status: "done"; data: string[] };
type Action =
| { type: "start"; at: number }
| { type: "fail"; message: string }
| { type: "finish"; data: string[] };
function reducer(state: State, action: Action): State {
switch (action.type) {
case "start":
return { status: "loading", startedAt: action.at };
case "fail":
return state.status === "loading"
? { status: "failed", message: action.message }
: state;
case "finish":
return state.status === "loading"
? { status: "done", data: action.data }
: state;
}
}
console.log(reducer({ status: "idle" }, { type: "start", at: 1 }));{ status: 'loading', startedAt: 1 }The two unions work together. The state union means a done state always has data and never has a message, so the UI can read state.data after checking state.status. The guards on fail and finish ignore actions that arrive in the wrong state, which is a decision you can change to throw instead. This is the same idea as a state machine, written as plain types.
Pitfalls
The discriminant must be a literal type. If a member has type: string, narrowing by type does not eliminate the other members. Check that every member uses a literal and that none was widened by a missing as const.
Keep the payload shapes flat and named. A nested payload object makes the narrowing work the same but adds noise at each use. Different fields per action, as shown, read better.
Do not mutate state in a reducer. Types do not catch this. Return new objects and arrays, as the examples do with spread and filter.
When you review a reducer, read the action union first. It works as the list of everything that can happen in this part of the program, and a long or confusing union is a sign that the state is doing too many jobs. Splitting one large reducer into two smaller ones, each with its own union, usually makes both easier to type and to test. Each reducer then handles a small set of actions, the compiler checks each switch for completeness, and a new teammate can learn the behavior by reading two short types instead of tracing a long function.


