← All Exercises
Exhaustive Reducer with assertNever
intermediatetypescript
Background
Reducers are the core of predictable state management. Exhaustive checking turns a forgotten action variant into a compile-time error instead of a silent no-op at runtime.
Problem
Define State with count and history, and an Action union covering increment (with by), decrement, set (with value), and reset. Implement reducer(state, action) so every case returns a new state with the new count appended to history, and the default branch calls assertNever(action). Apply a list of actions to an initial state.
Input
A JSON object with initial (a number) and actions (an array of action objects).
Output
A JSON object with the final count and the history of counts after each action.
Sample tests
Sample 1
Input: {"initial":0,"actions":[{"type":"increment","by":2},{"type":"set","value":10},{"type":"decrement"},{"type":"reset"}]}Expected: {"count":0,"history":[2,10,9,0]}Sample 2
Input: {"initial":5,"actions":[]}Expected: {"count":5,"history":[]}Sample 3
Input: {"initial":0,"actions":[{"type":"decrement"},{"type":"decrement"}]}Expected: {"count":-2,"history":[-1,-2]}Your solution
Learning objective
Use discriminated unions and exhaustive checking to make adding a union member a compile-time error.