Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use selectors in redux app with TypeScript?

I try to use selectors from reselect library in my Redux app.

my selectors file looks:

import { createSelector } from 'reselect'

const postsSelectors = state => state.global.posts.allPostse;

export const getPosts = createSelector(
  [ postsSelectors ],
  (posts) => posts
);

and then I try to use in my component, like this:

const mapStateToProps = (state) => ({
  posts: getPosts(state),
});

When I try to compile all of this, I got this error:

enter image description here

I'm guessing that with how I declare types for props, which currently looks like that:

interface Props{
 posts(state: any): any
 loadStories(): void;
};

Help me please resolve this issue. Thanks in advance.

like image 532
SuperManEver Avatar asked Feb 16 '17 20:02

SuperManEver


2 Answers

An example with more types:

  1. Describe types
type TPostData = {
  type: string;
};

type TPostsState = TPostData[];

type TState = {
  posts: TPostsState;
};
  1. Create selectors
// get all posts
export const selectPosts = (state: TState): TPostsState => state.posts;

// get new posts
export const selectNewPosts = createSelector<
  TState,
  TPostsState,
  TPostData[]>(
    selectPosts,
    (posts) => posts.filter(({ type }) => type === 'new'),
  );

Result: You've got all posts with type parameter 'new'.

like image 88
Ivan Stinsky Avatar answered Sep 24 '22 13:09

Ivan Stinsky


TypeScript is not expecting an array for the first argument. Just pass in your selector functions as arguments to createSelector, as in

export const getPosts = createSelector(
  postsSelectors,
  (posts) => posts
);
like image 42
Radio- Avatar answered Sep 23 '22 13:09

Radio-