how to use selectors in redux app with TypeScript?
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
);
An example with more types:
- Describe types
type TPostData = {
type: string;
};
type TPostsState = TPostData[];
type TState = {
posts: TPostsState;
};
- 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'.