如何指定useMemo中使用的函数的泛型类型作为参数?

时间:2019-08-25 21:22:04

标签: reactjs typescript function generics react-redux

我有一个通用功能,它是多个组件(根据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函数?

0 个答案:

没有答案