facebook / flow

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

Flow doesn't propagate refinement information through variable #7629

Open patrikniebur opened 5 years ago

patrikniebur commented 5 years ago

Flow version: 0.96.0

Expected behavior

Null check assigned to variable should prevent flow error: property missing in null

Actual behavior

Currently null checking is recognised in a statement if (myVar !== null) { console.log(myVar.prop); } but fails when assigned to a property:

 const isVarSet = myVar !== null;
if (isVarSet) { console.log(myVar.prop); }

I believe this issue is related too: https://github.com/facebook/flow/issues/7202

debel27 commented 5 years ago

I don't think this is a bug, nor even a desirable feature.

If you want to refactor a refinement, you can use predicate functions, like so :

if (isVarSet(myVar)) { console.log(myVar.prop); }

function isVarSet(myVar): boolean %checks {
  return myVar !== null;
}

Flow try

EDIT : I guess that OP would prefer this sort of syntax

const isVarSet: boolean %checks = myVar !== null;
if (isVarSet) { console.log(myVar.prop); }

But I'm unsure it is conceivable that assignments contribute to flow analysis.