如何正确键入重新映射的对象(使用选择器)



你好,我正在尝试创建useSelectors钩子,它应该与useSelector基本相同,但它应该接收并反对并返回一个对象。到目前为止,我为所有键正确键入了内容,但值未正确传递。

这是我的代码:

// useSelector.ts
const useSelectors = < U extends {} > (
selectors: {
[K in keyof U]: (state: Redux) => TypedUseSelectorHook < Redux > | null
},
): { [K in keyof U]: TypedUseSelectorHook<Redux> | null } => {
return reduce(
selectors,
(acc, selector, key) => {
return { ...acc,
[key]: useSelector(selector)
};
}, {},
);
};
// Component.tsx
const Component = () => {
const {
loading,
hierarchy,
error
} = useSelectors({
loading: selectHierarchyLoading,
hierarchy: selectHierarchyData,
error: selectHierarchyError,
})
return ...;
}

IDE 知道这些类型是如何的,因为它对我尖叫,我无法将这些类型分配给TypedUseSelectorHook,但我不知道如何传递它们,知道吗? :)

经过一些尝试,我让它工作了,如果有人对接收选择器对象并返回值对象的钩子感兴趣。

const useSelectors = < SelectorMap extends {} > (
selectors: {
[Selector in keyof SelectorMap]: (state: Redux) => SelectorMap[Selector]
},
): {
[Selector in keyof SelectorMap]: SelectorMap[Selector]
} => {
return reduce(
selectors,
(acc, selector, key) => {
return { ...acc,
[key]: useSelector(selector)
};
}, {}
as {
[Selector in keyof SelectorMap]: SelectorMap[Selector]
},
);
};

相关内容

  • 没有找到相关文章

最新更新