我有一个数组,可能有两种类型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)
})
Run Code Online (Sandbox Code Playgroud)
我可以添加类似的代码const itemA: A = item as any来console.log(itemA.propA)工作,但它看起来不优雅。
您的问题是 TypeScript 不够智能,无法检测到A过滤后数组的所有元素都应该是类型。您需要将过滤器函数的返回类型声明为item is A。请参阅此处的文档。
固定版本:
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)
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1256 次 |
| 最近记录: |