Blog>
Snippets

Strongly Typed State Selectors

Showcase how to create strongly typed selectors using `createSelector` from `reselect` library in conjunction with TypeScript for optimized and type-checked state selection.
import { createSelector } from 'reselect';

// Assume a State interface is already defined to represent the application state
interface State {
  user: {
    name: string;
    age: number;
  };
  products: {
    list: Array<{ id: number; name: string; price: number; }>;
  };
}

// Selector to get the user object
const selectUser = (state: State) => state.user;

// Selector to get the products list
const selectProducts = (state: State) => state.products.list;

// Create a strongly typed selector to get the user's name
export const selectUserName = createSelector(
  [selectUser],
  (user) => user.name
);

// Create a strongly typed selector for retrieving the total price of all products
export const selectTotalProductsPrice = createSelector(
  [selectProducts],
  (products) => products.reduce((total, product) => total + product.price, 0)
);
In this TypeScript example, we first define a `State` interface representing the shape of the application state. We then create simple selectors to access the `user` object and the `products` list from the state. Lastly, we use the `createSelector` function from the `reselect` library to create optimized and strongly typed derived selectors: `selectUserName` returns the user's name from the user object, and `selectTotalProductsPrice` calculates the total price of all products in the products list.