facebook / flow

Adds static typing to JavaScript to improve developer productivity and code quality.
https://flow.org/
MIT License
22.07k stars 1.86k forks source link

Object destructuring breaks disjoint union type. #3932

Open AndrewSouthpaw opened 7 years ago

AndrewSouthpaw commented 7 years ago

As an example:

type Props =
  | { type: 'foo', item: { id: number, parentId: number | null } }
  | { type: 'bar', item: { id: number, parentId: number } }

function test(props: Props) {
  // This works
  const yay = props.type === 'foo'
    ? props.item.id
    : `/parents/${props.item.parentId}/items/${props.item.id}`

  // This does not
  const { type, item } = props
  const boo = type === 'foo'
    ? item.id
    : `/parents/${item.parentId}/items/${item.id}`
}

I'm running v0.46. Curiously, the try flow REPL doesn't exhibit an error, I'm only getting it locally.

Any ideas?

vkurchatkin commented 7 years ago

This shouldn't really work. When you destructure a union, types get flattened.

AndrewSouthpaw commented 7 years ago

Hmm... I guess that makes sense. Thanks for pointing that out. I imagine it would be hard/impossible to keep the union with destructuring?

iddan commented 6 years ago

@vkurchatkin Why is that?

villesau commented 5 years ago

Some related issues: https://github.com/facebook/flow/issues/6146 https://github.com/facebook/flow/issues/6805 https://github.com/facebook/flow/issues/6594 https://github.com/facebook/flow/issues/6408 https://github.com/facebook/flow/issues/5745 https://github.com/facebook/flow/issues/4772