代码可以尝试here
我有一个类型是联合类型的交集:
type Location = {
latitude: number,
longitude: number
} & ({
locationType: 'country',
country: string
} | {
locationType: 'state',
state:string
})
我有另一个函数,它基于一种联合类型做某事:
const getLocationValue = (location: Location): string => {
if (location.locationType === 'country')
return location.country
else
return location.state
}
但是,这给了我错误:
property 国家 . 无法在任何交叉点类型的成员上访问属性
^属性 state
. 无法在任何交叉点类型的成员上访问属性
Flow应该能够理解,如果locationType是country,那么它应该有一个country属性 .
我究竟做错了什么?
1 回答
为了使用disjoint union Flow需要2种类型之间进行选择 . 目前,您只定义了一种类型:
Location
. 您可以将公共值拆分为一种"abstract"类型,并使Location
成为真正的类型并集,以便使Flow能够在它们之间进行选择 . 它可能如下所示:试试吧:在flow.org上working example