Type refinement information is "lost" within callbacks that are known to be executed immediately
Consider the following fragment (http://tryflow.org/#b86b73b2deee7f1be526f6c32c227ab2):
var arr: ?Array<number> = [];
if (arr) {
arr.sort(); // ok
[1,2,3].forEach(num => arr.push(num)); // Flow error: arr can be null
}
Within the if block Flow knows that arr cannot be null. However when it comes to executing the callback within forEach, that information is no longer known.
Of course, for arbitrary callback-accepting functions this is a right thing to do -- however Array's iterators are not arbitrary: they are executed immediately and synchronously. Given their ubiquity, it would be nice if Flow knew about Array's map, filter, forEach, etc. and propagated any type information into the callbacks accepted by these functions.
If you use const, Flow will keep the refinement even in the callback. We still don't have a way to annotate a callback as immediately invoked, so leaving this open.
Seems like another instance of this error:
coversAll(vv: ?string | ?VVector): boolean {
if (!vv) {
return true;
}
if (!(vv instanceof VVector)) {
vv = new VVector(vv);
}
var keys = Object.keys(vv.map)
var map = this.map;
return keys.every(function(key){
return map.hasOwnProperty(key) && map[key] > vv.map[key];
});
}
fails with:
src/VVector.js:104
104: return map.hasOwnProperty(key) && map[key] > vv.map[key];
^^^ property `map`. Property cannot be accessed on possibly null value
104: return map.hasOwnProperty(key) && map[key] > vv.map[key];
^^ null
src/VVector.js:104
104: return map.hasOwnProperty(key) && map[key] > vv.map[key];
^^^ property `map`. Property cannot be accessed on possibly undefined value
104: return map.hasOwnProperty(key) && map[key] > vv.map[key];
^^ undefined
src/VVector.js:104
104: return map.hasOwnProperty(key) && map[key] > vv.map[key];
^^^ property `map`. Property not found in
104: return map.hasOwnProperty(key) && map[key] > vv.map[key];
^^ String
This doesn't require annotating callbacks as immediately executing, does it?
Flow is doing the right thing here. What if?
arr.sort = () => {
arr = null;
};
While unlikely, in this case you could not push to null. As @samwgoldman recommended, you need to make arr const and this error can’t happen 😊
@andreypopp your case is similar since arguments are not constant by default. If you’d like we have a setting that makes Flow assume that all arguments are constant. experimental.const_params .