Comparing a string variable to a literal does not refine its type
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;
}
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!
}
}
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;
}
}
@samwgoldman Do you know what's going on here?
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...
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.
Thanks, this was really helpful!