Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 45

Typing `useReducer` with Discriminated Unions

Recommended resources

Hello! Welcome to our next lesson on advanced state management with React and TypeScript.

In our last session, we introduced the useReducer hook as a powerful tool for managing complex, interdependent state. We saw how it helps centralize all state transition logic into a single reducer function, making our components cleaner and more predictable.

We ended with a simple TypeScript definition for our actions, like this:

interface Action {
  type: 'increment' | 'decrement';
}

This works, but it has a major limitation: what happens when an action needs to carry data? For instance, an action to add a todo item needs the todo's text, or an action to set a counter's value needs the new value. The simple Action type can't handle this gracefully.

Today, we'll solve this problem. Our goal is to define types for useReducer state and actions using discriminated unions. This powerful TypeScript pattern will allow you to create highly specific and type-safe actions, where each action can have a different data payload, giving you fantastic autocompletion and preventing a whole class of bugs.

1. The Problem: Typing Actions with Payloads

Let's continue with our counter example. Suppose we want to add two new actions:

  1. 'reset': Resets the count to its initial value. This action needs no extra data.
  2. 'set': Sets the count to a specific number. This action needs to carry that number as a payload.

A common first attempt to type this might be to add an optional payload property to our Action interface:

interface Action {
  type: 'increment' | 'decrement' | 'reset' | 'set';
  payload?: number; // Optional payload
}

This seems plausible, but it introduces ambiguity and weakens our type safety.

React TypeScript Tutorial - 13 - useReducer Strict Action Types

To see why this approach is problematic, let's watch a short segment from Codevolution's React TypeScript series. It clearly demonstrates the type errors and logical inconsistencies that arise from using a simple optional property for payloads.

Please watch from 01:34 to 04:02. Notice how making the payload optional for the 'reset' action causes TypeScript to complain when you try to use the payload for the 'increment' and 'decrement' actions, as it could now be undefined.

As the video illustrates, this approach creates two main issues:

  1. Unnecessary Checks: For actions that do use a payload (like 'set'), TypeScript will force you to check if action.payload is undefined, even though you know it will always be there for that specific action type. This adds noise to your reducer logic.
  2. Invalid Dispatches: It allows you to dispatch actions that don't make sense, such as dispatch({ type: 'reset', payload: 10 }). The 'reset' action shouldn't have a payload, but our type definition allows it. Our types are not accurately describing our intent.

We need a way to tell TypeScript that the payload property should only exist and be required for the 'set' action, and should not exist for the other actions.


2. The Solution: Discriminated Unions

The correct and idiomatic way to type reducer actions in TypeScript is with a discriminated union. This pattern allows you to combine several different object types into one single union type, where a common property (the "discriminant") is used to tell them apart.

In our case, the type property of our actions is the perfect discriminant.

TypeScript Discriminated Unions Visual
This image visually represents the core idea of discriminated unions. By checking a common property (like 'shape'), TypeScript can narrow down the type to a more specific one, enabling safer access to other properties.

Here’s how you would define the actions for our counter using a discriminated union:

// Define a specific type for each action
type UpdateAction = {
  type: 'increment' | 'decrement';
};

type ResetAction = {
  type: 'reset';
};

type SetAction = {
  type: 'set';
  payload: number; // Payload is REQUIRED for this action
};

// Create the union of all possible actions
type CounterAction = UpdateAction | ResetAction | SetAction;

Note: It's also common to define these inline without the intermediate type aliases, which we'll see in later examples.

This structure is incredibly powerful. We've created a single CounterAction type that precisely describes all possible events that can happen to our state.

React TypeScript Tutorial - 13 - useReducer Strict Action Types

Let's see the solution in action. The same video from Codevolution now introduces this exact pattern.

Watch from 04:02 to 05:27. This short clip shows how to create separate types for actions with and without payloads and combine them into a single union type, resolving all the previous type errors.

How It Works in the Reducer

When you use this CounterAction type in your reducer, TypeScript's control flow analysis shines. Inside a switch (action.type) statement, TypeScript automatically narrows the type of action within each case block.

function counterReducer(state: State, action: CounterAction): State {
  switch (action.type) {
    case 'increment':
    case 'decrement':
      // Here, TypeScript knows `action` is of type `UpdateAction`.
      // Trying to access `action.payload` would result in a compile-time error!
      return { ...state, count: state.count + (action.type === 'increment' ? 1 : -1) };

    case 'reset':
      // Here, TypeScript knows `action` is of type `ResetAction`.
      return { count: 0 };

    case 'set':
      // Here, TypeScript knows `action` is of type `SetAction`.
      // It knows `action.payload` exists and is a `number`. No optional chaining needed!
      return { count: action.payload };

    default:
      return state;
  }
}

This pattern eliminates all the ambiguity. It's impossible to access a payload that doesn't exist for a given action, and it's impossible to forget a payload for an action that requires one.


3. A Complete Example: Todo List

Discriminated unions truly prove their worth in more complex scenarios. Let's analyze a full-fledged example: a todo list. This application will have state for the todos themselves and a visibility filter. It will need actions for adding a todo, toggling a todo's completion status, and changing the filter.

Type-checking React useReducer in TypeScript

This article by Ben Ilegbodu provides a fantastic, in-depth walkthrough of type-checking useReducer for a todo list application. It's a perfect real-world demonstration of the concepts we've just discussed.

Please read the sections with the full code example and the subsequent breakdown. Start from the large code block showing the full component and read through to the end of the explanation of the reducer function. Focus on: How the State interface is defined. How the Action type is defined as a discriminated union for add_todo, toggle_todo, and set_visibility. The explanation of how TypeScript provides type safety and exhaustiveness checking within the reducer's switch statement.

Let's summarize the key type definitions from that article:

1. The State Type: The shape of the entire state object is explicitly defined.

type Visibility = 'all' | 'completed' | 'active';

interface State {
  todos: {
    id: number;
    text: string;
    completed: boolean;
  }[];
  visibility: Visibility;
}

2. The Action Discriminated Union: This is the core of our typing strategy. Each action has a distinct shape.

type Action =
  | { type: 'add_todo'; id: number; text: string }
  | { type: 'toggle_todo'; id: number }
  | { type: 'set_visibility'; visibility: Visibility };

Notice how 'add_todo' requires an id and text, 'toggle_todo' only requires an id, and 'set_visibility' requires a visibility string. These types perfectly model our application's events. When you use the dispatch function, TypeScript will ensure you provide the correct properties for the action type you're dispatching.

Test your understanding!

Based on the Action type for the todo list above, which of the following dispatch calls would cause a TypeScript error, and why?

  1. dispatch({ type: 'add_todo', text: 'Learn TypeScript' })
  2. dispatch({ type: 'toggle_todo', id: 123 })
  3. dispatch({ type: 'set_visibility', visibility: 'done' })
  4. dispatch({ type: 'add_todo', id: 456, text: 'Master React', completed: false })
Show answer

The calls that would cause errors are 1, 3, and 4.

  1. Error: dispatch({ type: 'add_todo', text: 'Learn TypeScript' }) is missing the required id property for the 'add_todo' action.
  2. Correct: This call is valid. The 'toggle_todo' action requires only an id.
  3. Error: dispatch({ type: 'set_visibility', visibility: 'done' }) has an invalid value for the visibility property. The Visibility type only allows 'all', 'completed', or 'active'.
  4. Error: dispatch({ type: 'add_todo', id: 456, text: 'Master React', completed: false }) includes an extraneous completed property. The type for 'add_todo' does not include this property.

4. Advanced Pattern: Typing State with Discriminated Unions

Just as we can use discriminated unions for actions, we can also use them to represent the state itself. This is a powerful technique for making "illegal states unrepresentable."

Consider a state that manages data fetching. It could have statuses like 'loading', 'success', or 'error'. A naive approach might be:

interface State {
  status: 'loading' | 'success' | 'error';
  data?: DataType;   // Optional data
  error?: string;    // Optional error
}

The problem here is that you could have a state where status is 'success' but data is undefined, or status is 'loading' but an error message is present. These states don't make sense.

A better way is to use a discriminated union for the state itself.

Typing a usereducer react hook in typescript

The article from Sumo Logic, which we've referenced before, has an excellent section on this advanced pattern. It refactors the state definition to be more precise and prevent impossible state combinations.

Please read the short section titled "useReducer React hook: State representation". It's near the end of the article. Pay attention to how the State type is redefined using a status discriminant to ensure that data only exists when the status is 'success', and error only exists when the status is 'error'.

The improved state type looks like this:

type State =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'success', data: HNResponse }
  | { status: 'error', error: string };

With this definition, if state.status is 'success', TypeScript knows that state.data is available. If state.status is 'loading', you can't even try to access state.data or state.error. This makes your component's rendering logic much safer and more robust.


Conclusion

Today you've leveled up your TypeScript and React skills significantly. By moving beyond simple action types and embracing discriminated unions, you can make your useReducer implementation incredibly robust and developer-friendly.

Key Takeaways:

  • Using simple optional payloads (payload?: ...) for reducer actions leads to type ambiguity and allows invalid action dispatches.
  • Discriminated unions are the standard pattern for typing useReducer actions in TypeScript. They create a union of specific object types, each distinguished by a common property with a literal type (e.g., type: 'add_todo').
  • This pattern enables TypeScript to perform type narrowing within switch statements, ensuring you can only access the properties that are valid for the specific action being handled.
  • You gain compile-time safety, preventing you from dispatching malformed actions or accessing non-existent properties in your reducer.
  • This same pattern can be applied to the State type itself to make impossible state combinations unrepresentable, further increasing the robustness of your code.

Preview of the Next Lesson:
We've now built a powerful, self-contained state management machine with useReducer. But so far, this state is local to a single component. What if multiple, deeply nested components need access to this state or need to dispatch actions? In our next lesson, we will learn how to combine useReducer and useContext to create a scalable state management solution, broadcasting our state and dispatch function throughout a component tree.