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.
We'll cover the following...
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:
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:
But now, TypeScript will never be sure if ...