如何在Redux应用程序中使用TypeScript选择器?

blmhpbnm  于 2022-11-24  发布在  TypeScript
关注(0)|答案(3)|浏览(147)

我尝试在Redux应用程序中使用来自重新选择库的selectors
我的选择器文件看起来:

import { createSelector } from 'reselect'

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

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

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

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

当我试图编译所有这些代码时,出现了以下错误:

我猜,根据我为props声明类型的方式,目前看起来是这样的:

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

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

xkftehaa

xkftehaa1#

更多类型的示例:
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'的帖子。

d4so4syb

d4so4syb2#

TypeScript的第一个参数不需要数组。只需将选择器函数作为参数传递给createSelector,如下所示

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

utugiqy63#

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或尝试在tsconfig.json文件中设置"declaration": false编译器选项。

相关问题