我有一个可能有两种类型的数组 A
和 B
.我想对一种类型的项目执行操作。
type A = {
propA: number
}
type B = {
propB: string
}
type MyArray = Array<A|B>
const anArrayOfBothAAndB: MyArray = [{ propA: 1 }, { propB: '2' }]
anArrayOfBothAAndB.filter((item) => {
return (item as A).propA
})
.forEach((item: A) => { // reports error here
console.log(item.propA)
})
我可以添加类似 const itemA: A = item as any
的代码制作console.log(itemA.propA)
工作,但看起来不优雅。
最佳答案
您的问题是 TypeScript 不够智能,无法检测到数组的所有元素在过滤后都应为 A
类型。您需要将过滤器函数的返回类型声明为item is A
。请参阅文档 here .
固定版本:
type A = {
propA: number
}
type B = {
propB: string
}
type MyArray = Array<A|B>
const anArrayOfBothAAndB: MyArray = [{ propA: 1 }, { propB: '2' }]
anArrayOfBothAAndB.filter((item): item is A => {
return (item as A).propA !== undefined
})
.forEach((item) => { // no more error, don't even have to specify type
console.log(item.propA)
})
关于typescript - 如何使用多种类型的数组进行过滤和执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60904952/