top | item 11845422

(no title)

alectic | 9 years ago

Jeff here (I work on Flow).

I talked a bit about why we infer unions in this way in my ReactEU talk earlier this week (https://www.youtube.com/watch?v=VEaDsKyDxkY).

Ultimately it boils down to the notion that inference is about understanding the type, and annotations are about expressing it.

If you write a type annotation for a variable, then Flow will of course not infer anything more or less than your annotation. If, however, you use the variable as multiple types (but do so in a way that is clearly safe), Flow infers the union so that it doesn't give you errors for code that is clearly ok.

I think the example from the talk was something like:

  var name = "Jeff";
  name = name.toUpperCase(); // safe
  if (loggedOut) {
    name = null; // safe
  }
  var firstInitial = name ? name[0] : null; // safe
The above code has no errors in it, and because flow infers `name` as a type `null | string`, Flow is able to verify its safety and thus doesn't error.

OTOH, if we use an annotation to express the type of `name` as intended as only `string`, then we would get an error on the null assignment:

thing like:

  var name: string = "Jeff";
  name = name.toUpperCase();
  if (loggedOut) {
    name = null; // Error!
  }
  var firstInitial = name ? name[0] : null;
So in summary: Inference is the means by which Flow understands, annotations are the means by which you express to Flow your intentions.

discuss

order

No comments yet.