2016-08-04 57 views
0

我不知道我在做什麼錯在這裏:流量抱怨減少返回一個布爾

export function subscriptionsReady(handles: Array<Object>): boolean { 
    if (handles.length === 1) return handles[0].ready(); 

    return handles.reduce((a: any, b: Object): boolean => { 
    return (typeof a === 'object' ? a.ready() : a) && b.ready(); 
    }); 
} 

流量錯誤:

9: return handles.reduce((a: any, b: Object): boolean => { 
      ^call of method `reduce` 
    9: return handles.reduce((a: any, b: Object): boolean => { 
      ^undefined (too few arguments, expected default/rest parameters). This type is incompatible with the expected return type of 
    6: export function subscriptionsReady(handles: Array<Object>): boolean { 
                   ^^^^^^^ boolean 
+0

這些類型記住,'reduce'可以在陣列中返回類型的值(在你的情況下'Object'型),如果有隻數組中的一個元素。我認爲這就是爲什麼流類型抱怨返回類型。也許提供'true'或'false'的初始值 – Doc

回答

2

這是因爲type definitionArray.prototype.reduce需要「備忘錄」或返回的布爾值與第二個參數匹配到.reduce()。然而

看來,你實際上是試圖檢查手柄中的每一個對象是.ready()在這種情況下,這可能對你會更好:

function subscriptionsReady(handles: Array<Object>): boolean { 
    return handles.every((handle): boolean => { 
    return handle.ready(); 
    }); 
} 

因爲Array.prototype.every是早已鍵入你實際上可以忽略大多數這些類型:

function subscriptionsReady(handles: Array<Object>) { 
    return handles.every(handle => handle.ready()); 
} 

和流將能夠推斷一切。

此外,您可能需要添加一個基本類型的手柄,而不是object這樣的:

type Handle = { ready(): boolean }; 

function subscriptionsReady(handles: Array<Handle>) { 
    return handles.every(handle => handle.ready()); 
} 

這將提高該得到流動時,誤用API產生的錯誤。

一般來說,你應該嘗試定義,而不是使用Object

2

https://github.com/facebook/flow/blob/master/lib/core.js#L204展望(其中超載簽名Array#reduce已聲明):

當您省略第二個argume時,返回類型爲reduce調用(以及傳遞給它的閉包) nt到reduce必須匹配元素類型Object。既然你把它作爲boolean,你必須傳入一個初始值boolean

您的代碼依靠動態檢查來區分這兩種情況,但這對於Flow來說太聰明瞭。