2016-12-02 92 views
0

我有一個標籤聯合類型定義,並且有在我的代碼,我想篩選到一個單一類型的位置。過濾聯盟類型爲單型

/* @flow */ 

type AbstractChange = { 
    base: string, 
}; 

type CreateChange = AbstractChange & { 
    kind: 'create', 
    createField: string, 
}; 

type UpdateChange = AbstractChange & { 
    kind: 'update', 
    updateField: string, 
}; 

type Change = CreateChange | UpdateChange; 

function test(changes: Change[]) { 
    let creates: CreateChange[] = changes.filter(c => c.kind === 'create'); 

    return creates; 
} 

遺憾的是,似乎沒有被允許,我得到的錯誤:

19: function test(changes: Change[]) { 
         ^intersection. This type is incompatible with 7: 

type CreateChange = AbstractChange & {       
            ^object type 

Here's一試流鏈路是否有幫助。

回答

1

filter是不是足夠聰明,明白這樣的細化,但它也許明白類型

function maybeCreateChange(c: Change): ?CreateChange { 
    return c.kind === 'create' ? c : null 
} 

function test(changes: Change[]): CreateChange[] { 
    return changes.map(maybeCreateChange).filter(Boolean) 
}