What is the Purpose of my Code?
I have a set of functions stored in an object like this:
const actions = {
foo: (state: string, action: {payload: string}) => {},
bar: (state: string, action: {payload: number}) => {},
baz: (state: string, action: {payload: boolean}) => {},
qux: (state: string) => {}
}
Additionally, I have created a generic type as follows:
type ActionMapper<T> = T extends (state: any, action: infer Action) => any
? Action extends {payload: infer P}
? (payload: P) => void
: VoidFunction
: never
The current functionality of this type involves: https://i.sstatic.net/7RwuM.png
This setup allows for extracting the data type of the action.payload
parameter from the actions.foo()
function.
I now aim to create a generic type that performs a similar task but across the entire actions
object.
Attempts Made So Far
I attempted to define a generic type with this structure:
type ActionsMapper<A> = Record<keyof A, ActionMapper<A[keyof A]>>
However, the outcome was not exactly what I had anticipated: https://i.sstatic.net/VM9mM.png https://i.sstatic.net/XQ7Tr.png
Instead of solely capturing the parameter type from actions.foo()
, it collects it from all functions and generates a type union. My objective is for the type of mappedActions.foo()
to be (payload: string) => void
.
You can check out the TypeScript Playground I utilized here: TypeScript Playground.