Flow: Enforcing second argument to be subset of the first one.

Created on 8 Jul 2016  ·  2Comments  ·  Source: facebook/flow

I am trying to define a merge function where first argument model is an arbitrary class or plain object and the second argument patch is a record containing subset (or all) of the fields from model type. I would like to define it such that flow will be able to detect type mismatches between model and patch fields if they occur. Here is my attempt to implement this:

/* @flow */

declare function merge <patch, model:patch & *>
  (state:model, changes:patch):model

export type Model = {
  value: string
}

const clear = (model:Model):Model =>
  merge(model, {value: null})

I would expect flow to error due to type mismatch of the value field when calling merge in the function clear. Instead flow reports no errors. I'm testing on my machine with 0.27.0 and on on try flow, presumable it runs latest & greatest:

https://flowtype.org/try/#0PQKgBAAgZgNg9gdzCYAoVATApgYxgQwCcswoBXAOxwBcBLOCsAWy0IHMSAeAB32pwAWAGmZxsMAFy9+AsADJkAPlRgwACgDO1PlglMxWGCMH4KHDVL6CAlHoMx0WAB7c4hamGoBPbiQCy9mAAvGAA3ipgAG74MGS6YFqEtGaoAL7oOAxaYHhYRMHq+uISAeK2pYbByqos7FhqRYYiodGx8RRkMDCp1qhAA

Needs docs

Most helpful comment

Can $Shape be documented and demystified ?

All 2 comments

Got a response from @marudor on IRC:

10:32 AM >(state: model, change: path) => model
10:35 AM → bhosmer joined ⇐ rmg_ quit
10:39 AM marudor: what dose that $Shape mean ?
10:39 AM $ indicates its private
10:39 AM $Shape means something that has the shape of model
10:40 AM as in subset.
10:40 AM If it includes a specific property it has to be just like the one typed

And it seems to work as expected with a following changes:

/* @flow */

declare function merge <model, patch:$Shape<model>>
  (state:model, changes:patch):model

export type Model = {
  value: string;
  selectionDirection: 'forward' | 'backward' | 'none';
}

const clear = (model:Model):Model =>
  merge(model, {value: null})

I get following errors:

12:   merge(model, {value: null})
                           ^ null. This type is incompatible with
7:   value: string;
            ^ string

https://flowtype.org/try/#0PQKgBAAgZgNg9gdzCYAoVATApgYxgQwCcswoBXAOxwBcBLOCsAWy0IHMSAeJubGAGjAAHfNRwALAFwASAMrj8QrN15YYAPnWowYABQBnaqKySefQRPwUO+ySLHiAlKdUx0WAB5C4hamGoAnkpgALKuYAC8YADe2mAAbvgwZCZghoS01gDccfpquHQMACK0xDT0FJJgAORQPghEGNVgAD41AEb4OADWDYRNrTUUDFjVOQC+6DgMhmB4WESRemZqkmF8zutqkVo6LOxYuisCMYnJqRRkMDDjjqhAA

Can $Shape be documented and demystified ?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mjj2000 picture mjj2000  ·  3Comments

cubika picture cubika  ·  3Comments

philikon picture philikon  ·  3Comments

l2silver picture l2silver  ·  3Comments

jamiebuilds picture jamiebuilds  ·  3Comments