流程-具有联合类型的交叉点错误:“无法在任何交叉点类型的成员上访问属性" [英] Flow - intersection with union types error: "Property cannot be accessed on any member of intersection type"
问题描述
代码可以尝试此处
我的类型是联合类型的交集:
I have a type that is an intersection of union types:
type Location = {
latitude: number,
longitude: number
} & ({
locationType: 'country',
country: string
} | {
locationType: 'state',
state:string
})
我还有另一个函数,该函数根据联合类型之一进行操作:
I have another function that does something based on one of the union types:
const getLocationValue = (location: Location): string => {
if (location.locationType === 'country')
return location.country
else
return location.state
}
但是,这给了我错误:
属性
country
.无法在路口类型的任何成员上访问属性
property
country
. Property cannot be accessed on any member of intersection type
^属性state
.无法在路口类型的任何成员上访问属性
^ property state
. Property cannot be accessed on any member of intersection type
Flow应该能够理解,如果locationType是country,那么它应该具有country属性.
Flow should be able to understand that if locationType is country, then it should have a country property.
我在做什么错了?
推荐答案
为了使用不相交联合流需要2种以上的类型可供选择.当前,您仅定义了一种类型:Location
.您可以将公用值划分为一种抽象"类型,并使Location
为真正的类型并集,以使Flow可以在它们之间进行选择.看起来可能如下所示:
In order to use a disjoint union Flow needs 2+ types between which to choose. Currently you have defined only a single type: Location
. You can split the common values into a sort of "abstract" type and make Location
a true type union in order to enable Flow to choose between them. It could look like the following:
type AbstractLocation = {
latitude: number,
longitude: number,
}
type CountryLocation = AbstractLocation & {
country: string,
locationType: 'country',
}
type StateLocation = AbstractLocation & {
locationType: 'state',
state: string,
}
type Location = CountryLocation | StateLocation
这篇关于流程-具有联合类型的交叉点错误:“无法在任何交叉点类型的成员上访问属性"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!