Search⌘ K
AI Features

Using Unions

Explore how to leverage TypeScript union types to define specific action types in React reducers. Understand how this approach eliminates errors and enables cleaner, more maintainable state management code by ensuring all action cases are handled explicitly.

We used some traditional patterns to get around the issue where our reducer ignored actions that it wasn’t explicitly told to look for, but what if we could use TypeScript to prevent that from happening in the first place?

Using union action types

Let’s assume that, in addition to increment and decrement the counter, we can reset it back to zero. This gives us three types of actions:

  • Increment

  • Decrement

  • Reset

We’ll start with Increment ...