如何将 createSelector 与参数和 Typescript 一起使用?

tom*_*ole 14 typescript reselect redux-toolkit

我用来redux-toolkit生成选择器。我想在我自己的带有参数的自定义选择器中使用它们reselect。但我不知道如何输入我的选择器的返回类型?

const selectOrganizationName = (id: string): ??? =>
  createSelector(
    [(state: RootState) => organizationSelectors.selectById(state, id)],
    organization => organization.name
  );

export default selectOrganizationName;
Run Code Online (Sandbox Code Playgroud)
Missing return type on function.eslint@typescript-eslint/explicit-module-boundary-types
Run Code Online (Sandbox Code Playgroud)

Lin*_*ste 20

请记住,此警告仅由于您的 ESLint 设置需要显式返回类型而出现。Typescript 能够正确推断类型。

当您调用该selectOrganizationName函数时,您将返回一个选择器,该选择器接受 aRootState并返回组织名称string | undefined

type Return = (state: RootState) => string | undefined;

const selectOrganizationName = (id: string): Return =>
  createSelector(
    [(state: RootState) => organizationSelectors.selectById(state, id)],
    (organization) => organization?.name
  );
Run Code Online (Sandbox Code Playgroud)

但是,您可能有很多要为其创建返回类型的选择器,因此您可以创建一个RootState自动包含您的帮助器类型,并且只需要您设置选择的类型。

type Selector<S> = (state: RootState) => S;

const selectOrganizationName = (id: string): Selector<string | undefined> =>
  createSelector(
    [(state: RootState) => organizationSelectors.selectById(state, id)],
    (organization) => organization?.name
  );
Run Code Online (Sandbox Code Playgroud)

Typescript Playground 链接

  • 这个答案将导致每次组件重新渲染时选择运行。对于参数化用例,make 模式是更好的方法 https://redux.js.org/recipes/computing-driven-data (7认同)
  • 选择者的规则是什么? (5认同)