Type-safe Selectors with createSelector
Craft a code example that shows how to create typed selectors using createSelector showing typed parameterized selectors.
import { createSelector } from 'reselect';
// Assume we have a RootState type that represents the shape of our entire Redux store state
interface RootState {
users: {
byId: {
[key: string]: { id: string; name: string; }
};
allIds: string[];
};
}
// Individual selectors to extract parts of the state
const selectUserEntities = (state: RootState) => state.users.byId;
const selectUserIds = (state: RootState) => state.users.allIds;
// createSelector can now be used to combine selectors and project derived data
// Here we are creating a typed selector that returns an array of user names
export const selectUserNames = createSelector(
[selectUserEntities, selectUserIds],
(usersById, userIds) => userIds.map(id => usersById[id].name)
);
This code example defines a typed selector called selectUserNames using reselect's createSelector function. It combines two individual selectors, selectUserEntities and selectUserIds, to compute an array of user names from the state. Both the state and the return types are explicitly declared for type safety.