flow
flow copied to clipboard
Flow breaks when checking type via Object.prototype.toString
Flow breaks in the following excerpt. This is modified from the "Dynamic code" example.
function getType(obj) {
return Object.prototype.toString.call(obj).slice(8,-1).toLowerCase();
}
function length(x) {
if (x) {
if (getType(x) === 'string')
{
return x.length; //Flow error: "Property length not found in Number"
}
return x
} else {
return 0;
}
}
var a, b = 10;
var total = length("Hello") + length(a) + length(b);
Hi, thanks for noting this! Adding refinements based on Object.prototype.toString.call as a feature request.
As an aside, note that it's unlikely Flow will acquire the ability a) detect the test behind a user function call, or b) statically evaluate the subsequent slicing, etc., in the example. The detectable form of the refinement would be an inline check of the unmodified return value, e.g.
if (Object.prototype.toString.call(x) === '[object String]')
{
return x.length;
}
I think this feature is basically a dupe for predicate types as described in: #34 Closing.