Typecheck createAction Redux helper

Viewed 766

I have Action type defined like this:

type Action =
    { type: 'DO_X' }
    |
    { type: 'DO_Y', payload: string }
    |
    { type: 'DO_Z', payload: number }

It's a union type where each member is a valid action.

Now I'd like to create a function createAction that accepts type and returns a new function that accepts payload.

const doZ = createAction('DO_Z')
console.log(doZ(42)) // { type: 'DO_Z', payload: 42 }

Here's my current implementation:

const createAction = (type: Action['type']) =>
  (payload?: any) =>
    ({ type, payload })

It typechecks type like I want to. How can I also typecheck payload? I want payload to match type of correct action based on type. For example, doZ should fail when called with a string because it's payload says that it accepts only number.

2 Answers
Related