Forgetful programmer

There are situations where one would like to cover all possible values of a variable using conditional cases. A good example of this situation is a typical reducer function. Let’s consider an example of a counter with simple actions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
type Action = 'increment' | 'decrement';

function reducer(state: number, action: Action): number {
if (action === 'increment') {
return state + 1;
} else {
return state - 1;
}
}

// Example use case:
const initialState = 1;
const actions = ['increment', 'increment', 'decrement'];
const nextState = actions.reduce(reducer, initialState);
console.log(nextState) // 2;

So far so good. Now, let’s see what happens when another kind of action is added – 'reset', which in effect should set the counter back to 0.

1
type Action = 'increment' | 'decrement' | 'reset';

Now, let’s assume that you forgot to update the reducer function. Considered example is overly simplistic, but maybe the codebase is large and you didn’t even know about the existance reducer at all.