Problem Statement
Model a reducer with exhaustive switch over a union of actions.
Explanation
Use a discriminated union of actions and a switch on action.type. Add a never check in the default branch so new actions must be handled or the build fails.
Code Solution
SolutionRead Only
type State = { count: number };
type Action =
| { type: 'inc' }
| { type: 'dec' }
| { type: 'add'; payload: number };
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'inc': return { count: state.count + 1 };
case 'dec': return { count: state.count - 1 };
case 'add': return { count: state.count + action.payload };
default: {
const _exhaustive: never = action; // compile-time guard
return state;
}
}
}