如何定义为我的应用程序键入的 createSelector 版本?

Dan*_*515 8 typescript react-redux reselect typescript-typings redux-toolkit

在 redux-toolkit 文档中,他们建议您创建以下定义,以便在使用 useSelector 挂钩时具有正确的类型:

export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
Run Code Online (Sandbox Code Playgroud)

这将使您不必键入具有根状态的所有选择器。

然而,当需要定义记忆选择器时,createSelector没有关于如何做类似事情的说明。有没有任何快捷方式,或者我必须手动输入每个记忆的选择器?

Fil*_*iss 1

我正在开发一个应用程序,我也想做同样的事情。对于我的需求,我只想要一个简单的选择器,所以我这样做了:

\n
// store.ts\n\n// \xe2\x80\xa6omitted store configuration\n\nexport type RootState = ReturnType<typeof store.getState>;\n\n// create a generic type called AppSelector\nexport type AppSelector<Return> = (state: RootState) => Return\n// create a custom `createSelector` that uses the type above\nexport const createAppSelector = <R>(selector: AppSelector<R>): AppSelector<R> => selector\n
Run Code Online (Sandbox Code Playgroud)\n

通过上面的类型,我们可以执行以下操作:

\n
const selectTitle: AppSelector<string> = (state) => state.title;\n// Note that using the AppSelector type requires you to always pass the return type argument\n// It\'s much easier to use the createAppSelector function\n// selectTitle and selectTitle2 accomplish the same thing\nconst selectTitle2 = createAppSelector((state) => state.title);\n
Run Code Online (Sandbox Code Playgroud)\n

当里面的时候createAppSelectorstate就会正确的有RootState类型。

\n

这种形式的局限性在于,与 不同createSelectorcreateAppSelector它只允许您创建单个选择器,并且不允许您组合或改变选择。

\n

希望有一天我们能有办法const createAppSelector: TypedCreateSelector<RootState> = createSelector;

\n