【发布时间】:2021-10-20 18:54:42
【问题描述】:
当使用Array.filter() 时,我不确定如何实现我在下面描述的内容。
我不想仅仅为此创建一个新类型(但如果没有其他办法,那也没关系):
interface GPSLocation {
lat: number
lng: number
}
interface House {
address: string
location?: GPSLocation
}
const house01: House = {
address: '123 street'
}
const house02: House = {
address: '123 street',
location: {
lat: 111.111,
lng: 222.222
}
}
const allHouses = [house01, house02]
// Infered by Typescript: const gpsLocationList: (GPSLocation | undefined)[]
// Expected: const gpsLocationList: (GPSLocation)[]
const gpsLocationList = allHouses.filter((house) => house.location !== undefined).map(house => house.location)
【问题讨论】:
-
你必须创建一个自定义守卫来告诉 TypeScript 返回的保证不包含未定义。它不能to infer it without a guard。请参阅stackoverflow.com/a/62033938/227299 及其游乐场链接
-
请不要关闭此 Why can't TypeScript infer type from filtered arrays? 的副本。从给定的链接中推断出解决方案并不简单,即使这是我为这个确切问题找到最终解决方案的方式。
-
添加了第三个使用 .flatMap() 的选项。仅供参考@JuanMendes
-
@ItayMaman 太棒了!
标签: typescript