flow icon indicating copy to clipboard operation
flow copied to clipboard

Flow breaks when checking type via Object.prototype.toString

Open RoyTinker opened this issue 11 years ago • 2 comments

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);

RoyTinker avatar Feb 03 '15 18:02 RoyTinker

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;
}

bhosmer avatar Feb 03 '15 19:02 bhosmer

I think this feature is basically a dupe for predicate types as described in: #34 Closing.

nmn avatar Mar 04 '17 04:03 nmn