我有一个通用功能,它是多个组件(根据https://react-redux.js.org/api/hooks#using-memoizing-selectors)使用的选择器创建器,如下所示:
const makeCharSelector = <Subscriptions extends UseCharSubscriptions>() =>
createSelector<[RootStore, string[]], SelectorState<Subscriptions>>(
[
(state: RootStore) => ({
hasChar: state.user.checked && state.user.authenticated && state.user.data.hasChar,
initialized: state.char.meta.initialized,
}),
(state: RootStore, subscriptions: string[]): CharSelectorState<Subscriptions> => {
const subs = castArray(subscriptions);
return zipObjectDeep(subs, at(state.char, subs)) as CharSelectorState<Subscriptions>;
},
{
path: 1,
argIndex: 2,
},
],
(basic: SelectorState<Subscriptions>, subscriptions: CharSelectorState<Subscriptions>) => {
basic.char = subscriptions;
return basic;
}
);
然后在自定义钩子中,我像这样使用它:
export function useChar<Subscriptions extends UseCharSubscriptions = DefaultSubscriptionsList>(
subscriptions: string[] = defaultSubscriptions
): CharSelectorState<Subscriptions> | null {
const selector = useMemo(makeCharSelector, []);
const state = useSelector((state: RootStore) => selector(state, subscriptions));
但是随后错误地推断出makeCharSelector
Subscriptions
泛型,因此我想通过使用组件Subscriptions
手动指定它。
问题是我不能这样写:
useMemo(makeCharSelector<Subscriptions>, [])
都不使用通用的useMemo
,因为它仅指定返回类型。
所以问题是如何正确地将Subscriptions
钩子中的useChar
泛型传递给makeCharSelector
函数?