Blog>
Snippets

Typing Redux State and Selectors

Demonstrate how to type the Redux state and create type-aware selectors that can be used throughout a TypeScript application for consistent state access.
// TypeScript types for the state
interface Todo {
  id: number;
  text: string;
  completed: boolean;
}

interface TodosState {
  todos: Todo[];
}

// Example Redux state
const initialState: TodosState = {
  todos: [
    { id: 1, text: 'Learn TypeScript', completed: false },
    { id: 2, text: 'Study Redux', completed: false },
    // ... other todos
  ],
};
Defines TypeScript interfaces for Todo items and the TodosState. An initialState is provided as an example of what the Redux state shape could look like.
// Selector to get all todos
const selectTodos = (state: TodosState) => state.todos;

// Selector to get completed todos using the type from the state
const selectCompletedTodos = (state: TodosState) => state.todos.filter(todo => todo.completed);

// Selector to get a specific todo by its id
const selectTodoById = (state: TodosState, id: number) => state.todos.find(todo => todo.id === id);
Creates type-aware selectors for accessing todos. 'selectTodos' returns all todos, 'selectCompletedTodos' returns completed todos, and 'selectTodoById' returns a todo by id.
// Example usage of the selectors in a component (React)
import React from 'react';
import { useSelector } from 'react-redux';

const TodoList: React.FC = () => {
  // Using the selector to get all todos
  const todos = useSelector(selectTodos);

  return (
    <ul>
      {todos.map((todo) => (
        <li key={todo.id}>{todo.text}</li>
      ))}
    </ul>
  );
};

export default TodoList;
Demonstrates how to use the 'selectTodos' selector within a React functional component with the 'useSelector' hook from react-redux.