typescript - 如何使用带有参数和 Typescript 的 createSelector?

标签 typescript redux-toolkit reselect

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

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

export default selectOrganizationName;
Missing return type on function.eslint@typescript-eslint/explicit-module-boundary-types

最佳答案

请记住,此警告仅由于需要显式返回类型的 ESLint 设置而出现。 Typescript 能够正确推断类型。
当您拨打 selectOrganizationName函数,你返回一个带有 RootState 的选择器并返回一个组织名称,即 string | undefined .

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

const selectOrganizationName = (id: string): Return =>
  createSelector(
    [(state: RootState) => organizationSelectors.selectById(state, id)],
    (organization) => organization?.name
  );
但是,您可能有很多要为其创建返回类型的选择器,因此您可以创建一个包含您的 RootState 的帮助器类型。自动,只需要您设置选择的类型。
type Selector<S> = (state: RootState) => S;

const selectOrganizationName = (id: string): Selector<string | undefined> =>
  createSelector(
    [(state: RootState) => organizationSelectors.selectById(state, id)],
    (organization) => organization?.name
  );
Typescript Playground Link

关于typescript - 如何使用带有参数和 Typescript 的 createSelector?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66553130/

相关文章:

reactjs - Redux:子操作后更新父组件数据

javascript - Openlayers 为所有功能设置与背景层完全相同的比例

typescript - 如何找到所有用某种装饰装饰的类?

reactjs - Redux 工具包 RTK 查询突变未获取返回数据

javascript - Jest 未能通过 'No element indexed' 的覆盖率报告

javascript - 在 createSelector 中使用钩子(Hook)安全吗?

javascript - react |使用创建选择器传递 Redux 状态并隐藏菜单项

android - 蓝牙串口 - Ionic 2

node.js - Google Protobuf - 在 Typescript 中从 JSON 反序列化

reactjs - 如何在 RTK 查询中自动重新获取数据