Using Unions

Learn how to use the union action type and remove the default case in the reducer.

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 and Decrement and address Reset later.

We’ve already added the ability to increment or decrement by a certain amount. Resetting the counter will be unusual—we can only reset it to zero. Let’s start with our two known quantities: Increment and Decrement. Instead of saying that the type property on an action can be any string, we can get a bit more specific.

In the following code, we use the union of 'Increment' | 'Decrement'. We’re now telling TypeScript that the type property on a CounterAction isn’t just any string but rather that it’s one of exactly two strings.

Get hands-on with 1400+ tech skills courses.