【发布时间】:2018-11-29 06:45:14
【问题描述】:
我正在尝试强类型化 globalizeSelectors 函数,该函数将转换 redux 选择器函数的映射,以便它们将接受 GlobalState 类型而不是基于 StateSlice 的键的 StateSlice 类型(其中 StateSlice表示它是 GlobalState 对象的属性之一)。
棘手的部分是选择器的返回类型都可以不同,我不太清楚如何键入这种变化(或者是否可能)。根据 typescript 文档,我猜这可能需要巧妙地使用 infer 运算符,但我的 typescript-fu 还没有达到那个水平。
这是我目前得到的: (顺便说一句,对于你的 reduxy 类型,不要介意这些选择器不处理 props 或其他 args 的事实——我已将其删除以简化这一点)
import { mapValues } from 'lodash'
// my (fake) redux state types
type SliceAState = { name: string }
type SliceBState = { isWhatever: boolean }
type GlobalState = {
a: SliceAState;
b: SliceBState;
}
type StateKey = keyof GlobalState
type Selector<TState, TResult> = (state: TState) => TResult
type StateSlice<TKey extends StateKey> = GlobalState[TKey]
type GlobalizedSelector<TResult> = Selector<GlobalState, TResult>
const globalizeSelector = <TKey extends StateKey, Result>(
sliceKey: TKey,
sliceSelector: Selector<StateSlice<TKey>, Result>
): GlobalizedSelector<Result> => state => sliceSelector(state[sliceKey])
// an example of a map of selectors as they might be exported from their source file
const sliceASelectors = {
getName: (state: SliceAState): string => state.name,
getNameLength: (state: SliceAState): number => state.name.length
}
// fake global state
const globalState: GlobalState = {
a: { name: 'My Name' },
b: { isWhatever: true }
}
// so this works...
const globalizedGetName = globalizeSelector('a', sliceASelectors.getName)
const globalizedNameResult: string = globalizedGetName(globalState)
const globalizedGetNameLength = globalizeSelector(
'a',
sliceASelectors.getNameLength
)
const globalizedNameLengthResult: number = globalizedGetNameLength(globalState)
/* but when I try to transform the map to globalize all its selectors,
I get type errors (although the implementation works as untyped
javascript):
*/
type SliceSelector<TKey extends StateKey, T> = T extends Selector<
StateSlice<TKey>,
infer R
>
? Selector<StateSlice<TKey>, R>
: never
const globalizeSelectors = <TKey extends StateKey, T>(
sliceKey: TKey,
sliceSelectors: {
[key: string]: SliceSelector<TKey, T>;
}
) => mapValues(sliceSelectors, s => globalizeSelector(sliceKey, s))
const globalized = globalizeSelectors('a', sliceASelectors)
/*_________________________________________^ TS Error:
Argument of type '{ getName: (state: SliceAState) => string; getNameLength: (state: SliceAState) => number; }' is not assignable to parameter of type '{ [key: string]: never; }'.
Property 'getName' is incompatible with index signature.
Type '(state: SliceAState) => string' is not assignable to type 'never'. [2345]
*/
const globalizedGetName2: string = globalized.getName(globalState)
【问题讨论】:
-
对答案有什么想法吗?如果您对此有任何疑问,请告诉我,我可以改进答案。
标签: typescript redux