Dealing with Different Kinds of Actions
Learn how to add different actions using union and some TypeScript features.
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:
Press + to interact
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 ...