Search⌘ K
AI Features

Dealing with Different Kinds of Actions

Explore how to handle multiple action types in React reducers by leveraging TypeScript's union types. Understand how to define distinct action objects with or without payloads, ensuring precise type checking and better state management in your applications.

Adding the Reset action

Earlier, we hinted that we might add a third type of action: the ability to Reset the counter back to zero. This action is much like the actions we saw at the beginning. It doesn’t need a payload. However, it might be tempting to do something like this:

TypeScript 4.9.5
type CounterAction = {
type: 'Increment' | 'Decrement' | 'Reset';
payload: {
amount: number;
};
};

We’ll notice that TypeScript is again upset that we risk returning undefined from our reducer. We’ll handle that in a moment. But first, we should address the fact that Reset doesn’t need a payload.

We don’t want to have to write something like this:

let state = counterReducer({ count: 5 }, { type: 'Reset', { payload: { amount: 0 } } });

We might be tempted to make the payload optional by adding a question mark (?) to its name:

TypeScript 4.9.5
type CounterAction = {
type: 'Increment' | 'Decrement' | 'Reset';
payload?: {
amount: number;
};
};

But now, TypeScript will never be sure if ...