gpt4 book ai didi

javascript - 流 - 与联合类型的交集错误 : "Property cannot be accessed on any member of intersection type"

转载 作者:行者123 更新时间:2023-11-29 19:03:42 24 4
gpt4 key购买 nike

代码可以试一下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 country. Property cannot be accessed on any member of intersection type

^ 属性状态。不能在交集类型的任何成员上访问属性

Flow 应该能够理解,如果 locationType 是 country,那么它应该有一个 country 属性。

我做错了什么?

最佳答案

为了使用 disjoint union Flow 需要 2 种以上的类型可供选择。目前您只定义了一个类型:Location。您可以将公共(public)值拆分为一种“抽象”类型,并使 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

试一试:working example在 flow.org 上

关于javascript - 流 - 与联合类型的交集错误 : "Property cannot be accessed on any member of intersection type",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44635326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com