I was expecting this code to type check in Flow as it does in TypeScript:
var onClick : (() => void) | (() => boolean);
onClick = () => { return true; }
Instead, I get this error:
4: onClick = () => { return true; }
^ function. Could not decide which case to select
3: var onClick : (() => void) | (() => boolean);
^ union type
Is there a general name for this design decision, and what is the reasoning behind it?
Is it possible to ask the Flow checker to infer the return type of a function from return statements?
You will need to either provide an explicit cast, e.g.:
type FuncV = () => void;
type FuncB = () => boolean;
var onClick : FuncV | FuncB;
onClick = (() => { return true; }: FuncB);
Or use an existential type, e.g.:
type Func<T: (void | string)> = () => T;
var f: Func<*>;
f = () => { return "hello"; };
var msg = f() + " world!"; // type checks against return value above
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With