flow icon indicating copy to clipboard operation
flow copied to clipboard

Unexpected $Shape behaviour with maybe types and null

Open kevanstannard opened this issue 8 years ago • 4 comments

This code:

type Person = {
  name: ?string,
  age: ?number,
};

const createPerson = (extra: $Shape<Person>): Person => Object.assign({
  name: null,
  age: null,
}, extra);

triggers an error string [1] is incompatible with null [2]

However, using undefined instead of null works:

type Person = {
  name: ?string,
  age: ?number,
};

const createPerson = (extra: $Shape<Person>): Person => Object.assign({
  name: undefined,
  age: undefined,
}, extra);

Any ideas?

Flow Try

kevanstannard avatar Apr 04 '18 05:04 kevanstannard

Strange, a work around for now seems to be:

- Object.assign({ name: null, age: null }, extra);
+ Object.assign({}, { name: null, age: null }, extra);

ghost avatar Apr 04 '18 10:04 ghost

this issue is still present in v0.96

whollacsek avatar Apr 10 '19 12:04 whollacsek

Piggybacking of @idiostruct 's solution, you can do a similar workaround when using the object spread operator. I.E:

function renderWithDefaults(overrides: $Shape<PropsType> = {}) {
  return render(
    <SomeComponent
      firstName="John"
      lastName="Doe"
      dob="01-01-1984"
      {...overrides}
    />
  )
}

...will cause Flow errors, however the following will not:

function renderWithDefaults(overrides: $Shape<PropsType> = {}) {
  return render(
    <SomeComponent
      {...{}}
      firstName="John"
      lastName="Doe"
      dob="01-01-1984"
      {...overrides}
    />
  )
}

flow: 0.92.0

fossage avatar Jun 27 '19 03:06 fossage

First, use $Partial instead of shape: https://flow.org/en/docs/types/utilities/#toc-partial

Second, you need to provide an annotation for the target of Object.assign, or more simply use spread instead:https://flow.org/try/#0PTAEAEDMBsHsHcBQiAuBPADgU1ABSwE4DOsAdqALygDeioopAhgLZYBcoA-ESgQJakA5gBo6oRoPZdSAV2YAjQqIC+AbmQBjMj1AaCWRiiz5iZSqAAUWAB69GHACS5GBFH0bQAPCZKkAfACUHD5mFH6gAPLyAFZYGigAdIxERHyCpBYWtPRMrByy0NCi9BJSBUWIysGEvgHCoDZ2AeqIIKAyRDhEGPqMACagAjwGfWyIWqQ6egZGIaQATOZWtgT2oE4ubh7eNWSB1abkYZbZDCxlMoXF4pL5lxX0CU+NqyrNyIhAA

gkz avatar Jan 05 '23 00:01 gkz