Search⌘ K
AI Features

Adding Types to the Reducer

Explore how to add strong typing to your React reducers using TypeScript. Understand how typing helps catch errors like missing returns or misspelled actions, leading to safer and more maintainable state management code.

Implementing types in the reducer

Adding TypeScript will protect us from some of the more obvious mistakes—by ensuring we both pass in the correct arguments and return the expected result. Both situations can be tricky to triage in our applications because they might not happen until after the user takes an action—like clicking a button in the UI. Let’s quickly add some types to our reducer:

Let’s explain the code sample above:

  • Lines 1–2: We define two type definitions: the CounterState of number type to represent the state’s shape and the CounterAction of string type to represent the action type.

  • Lines 4–5: We define two action creators: the incrementAction and the decrementAction.

  • ...