Blog>
Snippets

Typed Selectors for State Extraction

Implement typed selectors using TypeScript to ensure that the data extracted from the Redux store is type-safe, and developers can easily spot type issues.
interface RootState {
  user: {
    name: string;
    age: number;
  };
  settings: {
    theme: 'dark' | 'light';
  };
}

// A typed selector for extracting the user's name
export const selectUserName = (state: RootState): string => state.user.name;

// A typed selector for extracting the user's age
export const selectUserAge = (state: RootState): number => state.user.age;

// A typed selector for extracting the current theme
export const selectTheme = (state: RootState): 'dark' | 'light' => state.settings.theme;
Here we define the RootState interface, which represents the shape of our Redux state. We have also defined three typed selectors using TypeScript for getting the user's name, user's age, and the application's theme from the state which are type-safe, i.e., they will only return values of the specified type.
import { useSelector } from 'react-redux';

// Use the typed selectors within a React component
function UserProfile() {
  const userName = useSelector(selectUserName);
  const userAge = useSelector(selectUserAge);

  // userName is guaranteed to be a string
  // userAge is guaranteed to be a number

  return (
    <div>
      <p>User: {userName}</p>
      <p>Age: {userAge}</p>
    </div>
  );
}
This code shows how to use the previously defined typed selectors inside a React component with the help of the useSelector hook from react-redux. The userName and userAge constants will be appropriately typed, providing autocompletion and type-checking benefits while developing the application.
/* Redux Store setup example with typed selectors */

import { createStore } from 'redux';
import { rootReducer } from './reducers';

const store = createStore(rootReducer);

export default store;
An example of setting up the Redux store with the rootReducer (not shown here). This code would live in a separate file like store.ts where our RootState and selectors would be used.