Evanss
Evanss

Reputation: 23563

TypeScript type for return of Reselect Redux function?

Is it possible to define the return type of the createSelector function in Redux's Reselect?

I couldn't figure this out from the official docs: https://github.com/reduxjs/reselect#q-are-there-typescript-typings

This cheatsheet also doesn't seem to provide this: https://github.com/piotrwitek/react-redux-typescript-guide#selectors-with-reselect

import { createSelector } from 'reselect';

import { TodosState } from './reducer';

export const getTodos = (state: TodosState) => state.todos;

export const getTodosFilter = (state: TodosState) => state.todosFilter;

export const getFilteredTodos = createSelector(getTodos, getTodosFilter, (todos, todosFilter) => {
  switch (todosFilter) {
    case 'completed':
      return todos.filter(t => t.completed);
    case 'active':
      return todos.filter(t => !t.completed);

    default:
      return todos;
  }
});

If I know that the return from getFilteredTodos is something like this:

type Return = {
  text: string;
  completed: boolean;
}[]

Then can I define this?

Upvotes: 2

Views: 4552

Answers (1)

Evanss
Evanss

Reputation: 23563

You can define the return like so:

export const getFilteredTodos = createSelector(getTodos, getTodosFilter, (todos, todosFilter) : { text: string; completed: boolean; }[] => {
  switch (todosFilter) {
    case 'completed':
      return todos.filter(t => t.completed);
    case 'active':
      return todos.filter(t => !t.completed);

    default:
      return todos;
  }
});

Upvotes: 2

Related Questions