0

I'm using reducers in React using useReducer. I have several actions whose correct types require different generic parameters. However, I have to export a single Action type to use with the dispatch method everywhere. Taking a union of two types with different generic parameters does not seem to work:


type MyTable1 = {
    "a": "b",
    "c": "d"
}
type MyTable2 = {
    "e": "f",
    "g": "h"
}

type Action1<K extends keyof MyTable1> = {"type": "action1"; "val": MyTable1[K]}
type Action2<K extends keyof MyTable2> = {"type": "action1"; "val": MyTable2[K]}

type AllActions = Action1 | Action2;

TS Playground

Is it possible for this to work somehow?

My current workaround is to have dedicated methods with correct typings for creating the action types that need generic parameters. However, I still end up exporting the more weakly-typed action definitions, so it's possible for a client to dispatch a bad action.

Nate Glenn
  • 6,455
  • 8
  • 52
  • 95
  • You should probably just do `type AllActions = Action1 | Action2`. You want a type that contains all possible actions, so you should provide a generic value that will cover all values that user might ever need to pass into `dispatch`. Here when `"val"` when you pass an action into dispatch is any key of, for instance, `MyTable1`, so when listing all actions you should allow all keys of `MyTable1` to be passed – Alex Chashin Feb 19 '23 at 08:50

0 Answers0