1

I'm playing around with Facebook Flow and wonder, why does the following function not type check? It obviously uses a union type denoted by '|'.

declare var f: ((x: any) => number) | ((x: any) => string);    
function f(x) {
    if(true) {
        return 5;
    }
    else return 'hello';
}

The checker complains:

function
This type is incompatible with
union type

I know that it works when I annotate it like:

declare var f: (x: any) => number|string;

But why does the former annotation fail? Frankly, I haven't seen union types for function types anywhere so far, however, I don't see a theoretic reason why it shouldn't be allowed.

Nat Mote
  • 4,068
  • 18
  • 30
sleepomeno
  • 193
  • 8

1 Answers1

1

((x: any) => number) | ((x: any) => string) is a valid expression. It means f can be one of these two function signatures. eg.

f = function(x: any): number {return 0} will work

f = function(x: any): string {return 'hello'} will also work

(x: any) => number|string means the return value of the same function can be one of these types dynamically, which is the case here.

initialxy
  • 1,193
  • 8
  • 17