Try to search your question here, if you can't find : Ask Any Question Now ?

How to flow type an object map such that value must contain key

HomeCategory: stackoverflowHow to flow type an object map such that value must contain key
Avatarpragati asked 5 months ago

I’m trying to properly type (using Flow) a createReducer helper function for redux. I’ve used the code from redux-immutablejs as a starting point.

I’m trying to follow the advice from the flow docs about typing redux reducers, but wrap it in a helper function with the shorthand map style. The basic idea is:

Create a separate type for each action:

type FooAction = { type: "FOO", payload: boolean };
type BarAction = { type: "BAR", payload: string };

type Action = FooAction | BarAction;

Pass a js object map to createReducer to provide a reduction function for each action.

createReducer<Action>({}, {
  FOO: (state, action) => state,
  BAR: (state, action) => state,

What I’d like to see from the type system:

  1. Within the reducer function, action is typed correctly (FOO sees FooAction), such that misuse of the payload generates an error.
  2. Error if the map contains extra (invalid) keys
  3. Error if the map is missing keys (for the defined types)

The part I think I can’t quite figure out is, can I define a map type such that the key must contained by the value type?

type Action<T = string> = { type: T, payload: any };
type Reducer<S, A> = (state: S, action: A) => S;
type HandlerMap<S, T> = {
  [T]: Reducer<S, Action<T>>,

I don’t think the above quite works, because the generic T would contain all of the type strings, as opposed to referring to a single one.

See this example on try flow. I feel like it is pretty close, but I can’t quite get rid of all the type errors. Any flow wizards that can show me how it’s done?

1 Answers
Best Answer
AvatarMikhail answered 5 months ago
Your Answer

16 + 18 =

Popular Tags

WP Facebook Auto Publish Powered By :