1

我在玩 Facebook Flow 并想知道,为什么以下功能不进行类型检查?它显然使用了一个由“|”表示的联合类型。

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

检查员抱怨:

function
This type is incompatible with
union type

我知道当我像这样注释它时它会起作用:

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

但是为什么前面的注释会失败呢?坦率地说,到目前为止,我还没有在任何地方看到函数类型的联合类型,但是,我没有看到为什么它不应该被允许的理论上的原因。

4

1 回答 1

1

((x: any) => number) | ((x: any) => string)是一个有效的表达式。这意味着f可以是这两个函数签名之一。例如。

f = function(x: any): number {return 0}将工作

f = function(x: any): string {return 'hello'}也将工作

(x: any) => number|string意味着同一个函数的返回值可以动态地是这些类型中的一种,这里就是这种情况。

于 2015-08-06T21:46:50.320 回答