可以尝试代码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
}
但是,这给了我错误:
属性
country
。无法在任何交集类型的成员上访问属性^属性
state
。无法在任何交集类型的成员上访问属性Flow应该能够理解,如果locationType是country,那么它应该具有country属性。
我究竟做错了什么?
最佳答案
为了使用disjoint union流,需要2种以上的类型进行选择。当前,您仅定义了一种类型:Location
。您可以将公用值划分为一种“抽象”类型,并使Location
为真正的类型并集,以使Flow可以在它们之间进行选择。看起来可能如下所示:
type AbstractLocation = {
latitude: number,
longitude: number,
}
type CountryLocation = AbstractLocation & {
country: string,
locationType: 'country',
}
type StateLocation = AbstractLocation & {
locationType: 'state',
state: string,
}
type Location = CountryLocation | StateLocation
尝试一下:flow.org上的working example