flow icon indicating copy to clipboard operation
flow copied to clipboard

Flow sometimes detects incorrect type in expressions involving && and ||

Open pasha-mf opened this issue 11 years ago • 4 comments

/* @flow */
class A {};
type B = {};

function foo(a: ?A, b: ?B) {
  var s: string = a && "X" || "Y"; // error
  var t: string = b && "X" || "Y"; // ok
}

Also, quite confusingly, the error is reported in parameter a of the function, instead of in the location where the parameter fails to typecheck: http://tryflow.org/#dd51333184c595d324852a62d95ed062

pasha-mf avatar Aug 28 '15 19:08 pasha-mf

Wow, nice catch!

Here's a trace:

test.js:5:18,18: A
This type is incompatible with
test.js:6:10,15: string
Error path:
test.js:5:18,18: InstanceT [A]
test.js:6:10,15: ~> StrT [string] comes from
test.js:5:18,18: . InstanceT [A]
test.js:6:19,33: . ~> PredicateT [||] comes from
test.js:5:18,18: . . InstanceT [A]
test.js:6:19,33: . . ~> OrT [||] comes from
test.js:5:18,18: . . . InstanceT [A]
test.js:6:19,26: . . . ~> PredicateT [&&] comes from
test.js:5:18,18: . . . . InstanceT [A]
test.js:6:19,26: . . . . ~> AndT [&&] comes from
test.js:6:19,19: . . . . . OpenT [A]
test.js:6:19,26: . . . . . ~> AndT [&&] comes from
test.js:6:19,19: . . . . . . AnnotT [A]
test.js:6:19,26: . . . . . . ~> AndT [&&] comes from
test.js:6:19,19: . . . . . . . MaybeT [?A]
test.js:6:19,26: . . . . . . . ~> AndT [&&]

I think the issue is in Flow_js.filter_not_exists, which doesn't consider InstanceT to be truthy, but I haven't actually tested this.

samwgoldman avatar Aug 28 '15 20:08 samwgoldman

All right, I had to check out an old-ish rev to make the change and test it, but adding an InstanceT case to filter_not_exists does indeed resolve this.

samwgoldman avatar Aug 28 '15 20:08 samwgoldman

This also fails:

/* @flow */

declare class Foo {}

function test(x: ?Class<Foo>): string {
  return x && "" || "";
}

samwgoldman avatar Aug 28 '15 20:08 samwgoldman

Glad you were able to solve it this fast!

pasha-mf avatar Aug 28 '15 20:08 pasha-mf