flow: function type using ExtractReturn

Viewed 297

I'm trying to reduce boilerplate of redux code typed with flow.

In particular, I want to avoid defining action types manually, but let flow deduce them from typed action creators, using the ExtractReturn tricks (as described for example in Shane Osbourne post or Martin Hochel post):

type _ExtractReturn<B, F: (...args: any[]) => B> = B;
type ExtractReturn<F> = _ExtractReturn<*, F>;

But it does not catch simple error, for example it should catch that action.id is a number and not a string: Try Flow.

If the action were defined "manually", error would be catched: Try Flow.

How can I have all errors properly catched in the reducer function, without writing manually boilerplate code?

  • Edit: fixed the Try flow links.
  • Edit: I didn't noticed that Shane Osbourne post provides a Flow Try that seems to work. Looking at it. Actually, it has the same problem. Trying on write a comment on the post to signal it. See comment here
1 Answers

If you're interested, I managed to get Flow to catch the error that your example didn't catch. Here is the code.

It's no doubt hacky. I got the idea from this Github issue.

Apart from that, I can't offer much more insight. I myself am looking for better solution.

Edit: After digging some more, I found that the $Call utility type can help a bit:

type Action =
  | $Call<typeof get, number>
  | $Call<typeof del, number>
  | $Call<typeof set, number, string>

After this, perhaps it's worth abstracting the $Call<...> pattern into a parametric type of its own. My knowledge of Flow at this point in time is limited, though, so my few attempts have not been fruitful.

Here is the full refactor.

Related