Course contentsShow
← React
Lesson 2385 of 2,39651. TypeScript with React BasicsFree lesson

Typing useReducer: State and Action Types

Define strongly-typed reducers with discriminated unions for actions and proper state types.

Typing useReducer: State and Action Types

You'll learn how to create fully type-safe reducers using discriminated unions for actions and explicit state types.

The Core Problem

When you use useReducer without TypeScript, your reducer can accidentally handle the wrong action types or produce invalid state. TypeScript can catch these errors at compile time—but only if you define proper types for both your state and actions.

Define State and Action Types

Start by defining your state interface and a discriminated union for actions:

interface CountState {
  count: number;
  lastAction: string;
}

type CountAction =
  | { type: 'increment' }
  | { type: 'decrement' }
  | { type: 'reset'; payload: number };

The union's type property acts as a discriminator—TypeScript uses it to narrow which action you're handling.

Type the Reducer Function

Your reducer function receives typed state and actions:

function countReducer(state: CountState, action: CountAction): CountState {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1, lastAction: 'increment' };
    case 'decrement':
      return { count: state.count - 1, lastAction: 'decrement' };
    case 'reset':
      // TypeScript knows action.payload exists here!
      return { count: action.payload, lastAction: 'reset' };
    default:
      return state; // Exhaustiveness check
  }
}

Use with useReducer

const [state, dispatch] = useReducer(countReducer, { count: 0, lastAction: 'init' });

// TypeScript enforces correct action shapes:
dispatch({ type: 'increment' }); // ✓
dispatch({ type: 'reset', payload: 10 }); // ✓
dispatch({ type: 'reset' }); // ✗ Error: payload required

The Analogy

Think of discriminated unions like a sorting machine: each action type opens a specific chute where TypeScript knows exactly what properties are available.

Key Takeaway: Use discriminated unions for actions and explicit state interfaces to make useReducer completely type-safe, catching action shape errors and state inconsistencies at compile time.