我到底想做什么?
我有一个物体,看起来像这样:
const actions = {
foo: (state: string, action: {payload: string}) => {},
bar: (state: string, action: {payload: number}) => {},
baz: (state: string, action: {payload: boolean}) => {},
qux: (state: string) => {}
}
我有一个泛型类型,如下所示:
type ActionMapper<T> = T extends (state: any, action: infer Action) => any
? Action extends {payload: infer P}
? (payload: P) => void
: VoidFunction
: never
The use case for this generic type works like this:
如您所见,它从actions.foo()
函数中提取action.payload
参数的类型.
我希望能够有一个泛型类型,它允许我做相同的事情,但对于整个actions
个对象.
我都试了些什么?
我try 创建如下所示的泛型类型:
type ActionsMapper<A> = Record<keyof A, ActionMapper<A[keyof A]>>
but it doesn't exactly do what I was expecting:
它不是只从actions.foo()
中提取参数类型,而是从每个函数中提取参数类型并创建类型联合.我想要的是mappedActions.foo()
的类型是(payload: string) => void
.
这是我使用的操场:TypeScript Playground.