Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't Flow deduce the type of a function based on what it returns?

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?

like image 415
Andrey Fedorov Avatar asked Jul 07 '17 20:07

Andrey Fedorov


1 Answers

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
like image 173
Rodris Avatar answered Oct 17 '22 01:10

Rodris