Course contentsShow
← React
Lesson 766 of 2,39620. useReducerFree lesson

Discriminated Unions with TypeScript

Typing actions as a union where type narrows payload shape, enabling exhaustive checking in the reducer switch.

Discriminated Unions with TypeScript

What you'll learn: How to use TypeScript discriminated unions to make action types safer and enable exhaustive checking in your reducer.

The Problem with Basic Action Typing

When you have multiple action types in a reducer, TypeScript needs to know that each action's payload shape depends on its type. Without discriminated unions, TypeScript can't narrow the payload type based on the action type, leading to unsafe access.

What is a Discriminated Union?

A discriminated union is a TypeScript pattern where you define multiple types that share a common "discriminant" property (like type). TypeScript uses this property to narrow which specific type you're working with.

Think of it like a vending machine: when you press button "A1", the machine knows to dispense a specific product with specific properties. Button "B2" dispenses something completely different. The button code is the discriminant.

How It Works with Actions

type Action =
  | { type: 'increment'; payload: { amount: number } }
  | { type: 'decrement'; payload: { amount: number } }
  | { type: 'reset'; payload: { value: number } }
  | { type: 'multiply'; payload: { factor: number } };

Now inside your reducer's switch statement, TypeScript automatically narrows the payload type:

function reducer(state: number, action: Action): number {
  switch (action.type) {
    case 'increment':
      // TypeScript knows payload.amount exists here
      return state + action.payload.amount;
    case 'decrement':
      return state - action.payload.amount;
    case 'reset':
      // TypeScript knows payload.value exists here
      return action.payload.value;
    case 'multiply':
      return state * action.payload.factor;
    default:
      return state;
  }
}

The Exhaustive Checking Benefit

If you add a new action type to your union but forget to handle it in the switch, TypeScript can catch this error. The discriminated union ensures every possible action is accounted for.

Key Takeaway: Discriminated unions make your reducer type-safe by letting TypeScript narrow the payload shape based on the action type, preventing runtime errors and enabling exhaustive checking.