facebook / flow

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

Flow unable to understand trivial variable equivalence when determining refinements #7228

Open rkrv opened 5 years ago

rkrv commented 5 years ago

I ran into a issue where flow will not recognise a type of a copied variable for conditional rendering in React:

https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoVBLAtgBzgJwBcwAlAUwEMBjYqfOLMAcn0pqYG50q4A7AZ2IAVMgA9iAXjAAKAN5gAFoSwwwAXwBcYeUpVbB+DLwDm6gJRgJAPkXKYXVFACuvGhj5gA6vgo4cZfDlbFXUtHTsAfn1CQxNzbVQwMB4BYgUKfgAJO0tg+0SwVkInfF5FDOyQgDIqsAAeEXE8iVldGDUwYCsuNVQgA

const Text = ({ html }: { html: string }) => html;

function Wrapper({ html }: { html?: string }) {
  const hasHtml = html;
  return hasHtml && <Text html={html} />;
}

Funny enough, this will work:

https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoVBLAtgBzgJwBcwAlAUwEMBjYqfOLMAcn0pqYG50q4A7AZ2IAVMgA9iAXjAAKAN5gAFoSwwwAXwBcYeUpVbB+DLwDm6gJRgJAPkXKYXVFACuvGhj5gA6vgo4cZfDlbFXUtHTsAfn1CQxNzbVQwMGBgMB4BYgUKfgAJO0tg+0SwVkInfF5CsAAyarAAHhFxQolZXRg1ZKsuNVQgA

const Text = ({ html }: { html: string }) => html;

function Wrapper({ html }: { html?: string }) {
  return html && <Text html={html} />;
}

Am I missing something?

TrySound commented 5 years ago

Refinements are not saved with new variables. It's expected behaviour. Just use already refined variable.

rkrv commented 5 years ago

Just use already refined variable.

That becomes complicated in larger scenarios, like:

const Text = ({ html, heading }: { html: string, heading: string }) => (
  <div>
    {heading}
    {html}
  </div>
);

function Wrapper({ html, heading }: { html?: string, heading?: string }) {
  const hasContent = html && heading;
  return hasContent && <Text html={html} heading={heading} />;
}
jbrown215 commented 5 years ago

Unfortunately, our refinement tracking is very conservative and cannot support your use case today. There is no one currently working on making our refinement tracking more complete.

rkrv commented 5 years ago

Thanks for your quick reply, @jbrown215! I'd be interested in helping with testing when somebody picks up this task.

villesau commented 5 years ago

@rkrv I got very definite answer to same problem here: https://github.com/facebook/flow/issues/6146#issuecomment-439139904

This has been reported many times already. I think that it's because the restriction is not well documented and the use case is pretty idiomatic JS. If you know the restriction, it's very easy to avoid it and still being able write clean code. Just avoid destructing objects that has this kind of "cross dependencies"