Blog>
Snippets

Strongly Typed Reducers in TypeScript

Create a redux reducer with TypeScript interfaces to strictly type the state and the action parameters, enhancing reducer function safety.
// Interfaces defining the shape of the state and the action
interface AppState {
  count: number;
}

interface Action {
  type: string;
  payload?: any;
}

// Action type constants
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';

// Strongly typed action creators
function incrementAction(): Action {
  return { type: INCREMENT };
}

function decrementAction(): Action {
  return { type: DECREMENT };
}
This code block defines the TypeScript interfaces for AppState and Action to ensure that the reducer function and action creators are strictly typed. It also defines action type constants and corresponding action creators.
// The initial state of the app
const initialState: AppState = {
  count: 0,
};

// The reducer function with strongly typed parameters
function counterReducer(state: AppState = initialState, action: Action): AppState {
  switch (action.type) {
    case INCREMENT:
      return { ...state, count: state.count + 1 };
    case DECREMENT:
      return { ...state, count: state.count - 1 };
    default:
      return state;
  }
}
This code block provides the initial state of the application and defines the strongly typed reducer function, which uses the AppState and Action interfaces to enforce type safety.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Strongly Typed Reducers in TypeScript</title>
  <script src="path_to_redux.js"></script>
  <!-- Include additional scripts such as React, ReactDOM, and Redux here -->
</head>
<body>
  <div id="app"></div>
  <!-- The rest of your application's HTML goes here -->
</body>
</html>
This HTML skeleton includes the Redux script and provides a container where the React application will be mounted.