2015-07-01 71 views
1

我正在玩Facebook流和奇怪,为什么以下功能不打字检查?它显然使用由'|'表示的联合类型。Facebook流量功能联盟类型

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; 

但为什么前者批注失败?坦率地说,到目前为止,我还没有看到函数类型的联合类型,但是我没有看到它不应该被允许的理论原因。

回答

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装置相同功能的返回值可以是这些类型的动态中的一个,其在这里是这样的。