Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flow: Typechecking a complex Immutable shape using fromJS()?

How do you typecheck the shape of an Immutable.JS data structure generated from fromJS using Flow? Plain old JS blobs can be typed very accurately using an object literal notation:

type ObjectShape = {
  a: number,
  b: string,
  c: {
    d: number,
  },
  e: Array<number>
};

const obj: ObjectShape = { // hyper-accurate
  a: 1,
  b: '2',
  c: {
    d: 3,
  },
  e: [4]
}

However, on the Immutable.js side, there seem to be two major complications:

  1. It appears that Immutable.js's fromJS method returns any (https://github.com/facebook/immutable-js/blob/master/type-definitions/immutable.js.flow#L764), so the following is not caught as an error in Flow:

    const map: boolean = fromJS(obj) // this is totally not true, but Flow can't tell
    
  2. It appears that map shapes cannot be described using an object-like notation per How to describe Immutable.js Map shape with Flow (or is this information outdated?).

I'm genuinely confused on how to get Flow to understand Immutable.js, maps in particular. From what I can tell, Flow loses a lot of intelligence about the codebase when the data is living within Immutable.js structures instead of plain JS primitives.

like image 675
Jon Cursi Avatar asked Feb 23 '17 08:02

Jon Cursi


1 Answers

EDIT 2018-05-14: The as-yet-unreleased version 4.0 of immutable-js has full support for this. When you create a Record, it will infer its type from the object passed to it, or you can manually type the factory as Record<TProps>. The latest release as of now is as 4.0.0-rc.9, but the project has been comatose for about six months, so you may want to just read up on the known bugs (to avoid them or, in a custom build, fix them) and use the RC.


You would theoretically have to use a Record() which encoded the expected shape and then add typechecking...

Except that statically typing the actual members of this immutable-js structure would sadly not be possible, because of certain features that are lacking in flow.

There is currently a pair of pull requests (first, second) open to add the necessary features to the typechecker, but they are fairly involved and the process of reviewing and integrating them seems to be going on internally at Facebook.

I suspect that as soon as those are merged, flow-typed definitions that encode the new hotness will be up almost immediately, even if the immutable-js project doesn't integrate them as fast.

Note: if you want to provide feedback, please do not leave "+1" or "when is it done comments"; those are not accepted style for that repository. Use the reaction/voting feature instead.

like image 122
azernik Avatar answered Sep 21 '22 13:09

azernik