如何对多种类型的数组进行过滤和执行?

Mik*_*ike 3 typescript

我有一个数组,可能有两种类型AB。我想对一种类型的项目执行操作。

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 anyconsole.log(itemA.propA)工作,但它看起来不优雅。

101*_*owz 8

您的问题是 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)