Course contentsShow
← TypeScript
Lesson 417 of 1,7969. Union TypesFree lesson

Discriminated Unions in Redux Actions

Typing Redux action objects as discriminated unions based on the action 'type' property.

Discriminated Unions in Redux Actions

What you'll learn: How to use discriminated unions to model Redux action objects in a type-safe way.

In Redux, actions are objects that describe state changes. Each action has a type property (like 'ADD_TODO' or 'DELETE_TODO') and potentially some data payload. Discriminated unions let TypeScript understand that when type is 'ADD_TODO', specific properties like text will be present, but when type is 'DELETE_TODO', you'll have an id instead.

Modeling Redux Actions as a Discriminated Union

Instead of typing every action separately, create a union of all possible actions with type as the discriminant:

type AddTodoAction = {
  type: 'ADD_TODO';
  text: string;
};

type DeleteTodoAction = {
  type: 'DELETE_TODO';
  id: number;
};

type ToggleTodoAction = {
  type: 'TOGGLE_TODO';
  id: number;
};

type TodoAction = AddTodoAction | DeleteTodoAction | ToggleTodoAction;

Type-Safe Reducers with switch

Now your reducer function gets automatic narrowing:

function todoReducer(state: any[], action: TodoAction) {
  switch (action.type) {
    case 'ADD_TODO':
      // TypeScript knows: action.text exists here
      return [...state, { text: action.text, done: false }];
    case 'DELETE_TODO':
      // TypeScript knows: action.id exists here
      return state.filter((todo, i) => i !== action.id);
    case 'TOGGLE_TODO':
      // TypeScript knows: action.id exists here
      return state; // simplified
  }
}

When you access action.text inside the 'ADD_TODO' case, TypeScript knows it exists. Try accessing action.text in the 'DELETE_TODO' case—TypeScript will error because that property doesn't exist there.

Key Takeaway: Discriminated unions model Redux actions as a type-safe union, letting TypeScript automatically narrow to the correct action shape based on the type property in your reducers.