Flow: Cannot override values when spreading

Created on 6 Apr 2018  路  7Comments  路  Source: facebook/flow

Try flow link

type A = {
  a: number
};

type B = {
  a: string
};

const testFn = (input: A): B => ({...input, a: 'uh oh :/'});

As you can see, the property a is overridden with string in the function. Both, input and output are type checked, but flow complains that output and input are not compatible. This is very basic and idiomatic ES6 behaviour and should be fully supported.

spread bug

Most helpful comment

@mrkev imho, this is not a feature request: it鈥檚 a bug. Flow鈥檚 understanding of the semantics of spread is simply incorrect, and inconsistent with its (correct) understanding of how field overriding works _without_ spread: namely, {a: 1, a: "won"} correctly has type {a: string} and not {a: number}.

All 7 comments

You can override values when spreading it's just that when the two types differ, flow infers the type to be an union of the two. This seems like reasonable behavior to me.

js const a: { a: (number | string) } = {...{a: 10}, a: 'no error'};

I think it's clear from the code that the result type of a can't be number anymore and flow should be able to infer it as string. It just can't be number after spreading anymore.

Imho this should work. If you need to replace a few of fields out multiple, then you can use rest operator as a _good engough_ workaround:

type A = {
  a: number,
  b: string,
  c: boolean
};

type B = {
  a: string,
  b: string,
  c: boolean
};

const testFn = ({a, ...rest}: A): B => ({...rest, a: 'works!'});

@mrkev imho, this is not a feature request: it鈥檚 a bug. Flow鈥檚 understanding of the semantics of spread is simply incorrect, and inconsistent with its (correct) understanding of how field overriding works _without_ spread: namely, {a: 1, a: "won"} correctly has type {a: string} and not {a: number}.

Yup, looks like it's buggy

I managed to make a PR to fix this: https://github.com/facebook/flow/pull/7298

This has been fixed and will typecheck in Flow v0.111.0

Was this page helpful?
0 / 5 - 0 ratings