state management in typescript

State management is an important aspect of building complex applications in TypeScript, especially in React applications. Redux is a popular state management library that provides a centralized store for managing the state of your application. To use Redux in a TypeScript project, you'll want to ensure that all your Redux actions, reducers, and state are properly typed.

The first step is to define your state interface with all the properties your application needs to store. For instance, if you're building a shopping cart application, your state might look something like this:

index.ts
interface AppState {
  cartItems: Array<{
    id: number;
    name: string;
    quantity: number;
    price: number;
  }>;
  totalPrice: number;
}
147 chars
10 lines

Next, you'll need to create your Redux actions using TypeScript's enum feature to define action types. For instance:

index.ts
enum CartActionTypes {
  ADD_ITEM = "ADD_ITEM",
  REMOVE_ITEM = "REMOVE_ITEM",
}
81 chars
5 lines

Then you can define your action interfaces, which describe the payload of each action:

index.ts
interface AddItemAction {
  type: CartActionTypes.ADD_ITEM;
  payload: {
    id: number;
    name: string;
    price: number;
  };
}

interface RemoveItemAction {
  type: CartActionTypes.REMOVE_ITEM;
  payload: {
    id: number;
  };
}
236 chars
16 lines

Finally, you can create your reducers, which take the current state and an action and return the new state. Here's an example reducer that handles the ADD_ITEM action:

index.ts
function cartReducer(state: AppState, action: AddItemAction | RemoveItemAction) {
  switch (action.type) {
    case CartActionTypes.ADD_ITEM:
      return {
        ...state,
        cartItems: [
          ...state.cartItems,
          {
            id: action.payload.id,
            name: action.payload.name,
            quantity: 1,
            price: action.payload.price,
          },
        ],
        totalPrice: state.totalPrice + action.payload.price,
      };
    default:
      return state;
  }
}
511 chars
21 lines

By typing all our actions and reducers, we ensure that our application works as expected, and we can take advantage of TypeScript's static analysis to catch errors early in development.

gistlibby LogSnag