flow icon indicating copy to clipboard operation
flow copied to clipboard

Comparing a string variable to a literal does not refine its type

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

The idea here is that I "know" that the str argument starts with either "a" or "b", and I want to enforce that knowledge through the use of invariant, but it doesn't seem to work.

/* @flow */
var invariant = require("invariant");

type Mode = "a" | "b";
function getMode(str: string): Mode {
  var ch = str[0];
  invariant(ch==="a" || ch==="b", "Wrong string passed");
  return ch;
}

pasha-mf avatar Oct 20 '15 22:10 pasha-mf

It looks like even simplest comparisons fail to refine:

// @flow
type Period = "year" | "month" | "day";
function cast(s: string): ?Period {
  if (s === "year") {
    return s; // nope, flow error!
  }
}

pasha-mf avatar Nov 19 '15 18:11 pasha-mf

Another example of the same issue occurs when using switch statements:

/* @flow */

type Color = "blue" | "yellow" | "red";

function test(color: Color) {
  switch (color) {
    case "red":
      (color: "red"); // Flow error
      break;

    case "blue":
    case "yellow":
      (color: "blue"|"yellow"); // Flow error
      break;
  }
}

pasha-mf avatar Dec 03 '15 02:12 pasha-mf

@samwgoldman Do you know what's going on here?

zgao avatar Dec 18 '15 01:12 zgao

This pattern simply isn't recognized by Flow. This docs page has the full list of refinements that Flow currently does. This just doesn't seem like a super high-value fix because you can replace the variable with the literal in each conditional to get the expected behavior.

This could be an interesting addition for someone from the community who is interested in hacking on Flow internals...

samwgoldman avatar Dec 18 '15 01:12 samwgoldman

The value of this pattern for me is to be able to convert an arbitrary string variable into an enumeration of fixed string symbols. For example suppose in your class you have a variable reindeer: "Dasher" | "Dancer" | "Prancer" | "Vixen" | "Comet" | "Cupid" | "Donner" | "Blitzen" | "Rudolph". Then a setter for that variable will look like this:

setReindeer(v: string) {
  if (v=="Dasher" || v=="Dancer" || v=="Prancer" || v=="Vixen" || v=="Comet" || 
      v=="Cupid" || v=="Donner" || v=="Blitzen" || v=="Rudolph") {
    this.reindeer = v; // In order for this to work, Flow should refine v to Reindeer type here
  }
}

Note that I can't declare the setter as setReindeer(v: Reindeer), since it will simply move the burden of checking the type correctness to the user of the class.

Right now there is no good solution to this problem, other than littering the code with unsafe typecasts or // $FlowIssue comments.

pasha-mf avatar Dec 24 '15 21:12 pasha-mf

Thanks, this was really helpful!

pasha-mf avatar Jan 21 '16 21:01 pasha-mf