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
屬性是布爾文字。
的意圖是用於流明白,如果conditional
是true
,則對象返回test
必須含有baz
,反之亦然。
這不可能嗎?