9

我尝试selectors在我的 Redux 应用程序中使用 reselect 库。

我的选择器文件看起来:

import { createSelector } from 'reselect'

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

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

然后我尝试在我的组件中使用,如下所示:

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

当我尝试编译所有这些时,我收到了这个错误:

在此处输入图像描述

我猜测我如何声明道具的类型,目前看起来像这样:

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

请帮我解决这个问题。提前致谢。

4

3 回答 3

9

更多类型的示例:

  1. 描述类型
type TPostData = {
  type: string;
};

type TPostsState = TPostData[];

type TState = {
  posts: TPostsState;
};
  1. 创建选择器
// 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'),
  );

结果:您得到了所有类型参数为“new”的帖子。

于 2020-05-30T20:59:16.603 回答
6

TypeScript 不希望第一个参数使用数组。只需将您的选择器函数作为参数传递给 createSelector,如

export const getPosts = createSelector(
  postsSelectors,
  (posts) => posts
);
于 2017-02-16T22:36:09.917 回答
0

如果reselect@4.1.5您使用的是typescript@≥4.2. 所以现在需要指定为:createSelector<Selectors extends SelectorArray, Result>

<Selectors extends SelectorArray, Result>

export type Selector<
  // The state can be anything
  State = any,
  // The result will be inferred
  Result = unknown,
  // There are either 0 params, or N params
  Params extends never | readonly any[] = any[]
  // If there are 0 params, type the function as just State in, Result out.
  // Otherwise, type it as State + Params in, Result out.
> = [Params] extends [never]
  ? (state: State) => Result
  : (state: State, ...params: Params) => Result

export type SelectorArray = ReadonlyArray<Selector>

例子:

// get all posts
export const selectPosts = (state: TState): TPostsState => state.posts;

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

但一般来说,对于较新的 TS,您现在不应该手动指定类型,因为它们会被自动推断。

如果您得到TS4023: Exported variable 'X' has or is using the name '$CombinedState' from external module,请参阅 Stackoverflow 答案https://stackoverflow.com/a/43901135/10963661或尝试"declaration": false在文件中设置编译器选项tsconfig.json

于 2021-12-01T10:44:17.450 回答