2017-08-04 21 views
0

流問題似乎爭取幾個答案,但這裏有雲:FlowJS:如何使用聯合類型和布爾文字

type Base = { 
    foo: string, 
    bar: string 
} 
type Derived1 = Base & { 
    conditional: false 
} 
type Derived2 = Base & { 
    conditional: true, 
    baz: string 
} 

type One = { 
    foo: string, 
    bar: string, 
    conditional: boolean 
} 
type Two = One & { 
    baz: string 
} 

type Return1 = Derived1 | Derived2 // fails 

type Return2 = One | Two // works, but not desired 

function test(conditional: boolean): Return1 { 
    return { 
    foo: "foo", 
    bar: "bar", 
    conditional, 
    ...conditional ? {baz: "baz"} : {} 
    } 
} 

最好是爲test返回值是Derived*類型之一(Return1而不是Return2),其中conditional屬性是布爾文字。

的意圖是用於流明白,如果conditionaltrue,則對象返回test必須含有baz,反之亦然。

這不可能嗎?

回答

1

流量不夠聰明,無法爲您解決問題。你必須做一些事情,如:

function test(conditional: boolean): Return1 { 

    const base = { 
    foo: "foo", 
    bar: "bar", 
    } 

    if (!conditional) { 
    return Object.assign({}, base, { conditional }); 
    } else { 
    const result: Derived2 = Object.assign({}, base, { conditional }, {baz: "baz"}); 
    return result; 
    } 
} 

此處瞭解詳情:https://flow.org/blog/2016/07/01/New-Unions-Intersections/