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

TypeScript: Discriminated Unions for Actions

Using union types for actions enables exhaustive type checking and better autocompletion.

TypeScript: Discriminated Unions for Actions

What you'll learn: How to use TypeScript's discriminated unions to make action types safer and get better IDE support when working with reducers.

The Problem with Loose Action Types

When you define actions as simple objects with type: string and payload: any, TypeScript can't help you much. It doesn't know which action types exist or what payload each action should carry.

Discriminated Unions: The Type-Safe Solution

A discriminated union is a TypeScript pattern where you define multiple specific types, each with a unique literal value in a common property (usually type). TypeScript can then "discriminate" between them automatically.

Think of it like a sorting machine that reads a package's label and knows exactly what's inside based on that label alone.

Defining Your Action Types

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

Now TypeScript knows exactly which actions exist and what data each carries.

The Magic: Exhaustive Checking

Inside your reducer's switch statement, TypeScript narrows the action type in each case:

function reducer(state: number, action: Action): number {
  switch (action.type) {
    case 'increment':
      return state + 1;
    case 'set':
      return action.payload; // TypeScript knows payload exists!
    // Forget a case? TypeScript error!
  }
}

Benefits You Get

  1. Autocompletion: Type action.type and see all valid strings
  2. Payload safety: Access action.payload only when it exists
  3. Exhaustiveness: TypeScript warns if you forget to handle an action type
  4. Refactoring confidence: Rename an action type and find all uses instantly

Key Takeaway: Discriminated unions turn your action types from loose strings into a type-safe contract, giving you compile-time guarantees and excellent IDE support throughout your reducer logic.