typescript - 如何使用多种类型的数组进行过滤和执行?

标签 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)
})

我可以添加类似 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/

相关文章:

Angular - 对象作为选择选项值

typescript - 在 TypeScript 中扩展接口(interface),其中 module=es6 导致 Property does not exist

angular - SheetJs 自动转换日期 Angular 7

generics - Typescript 中区分联合类型的通用匹配函数

javascript - 声明用于 TypeScript 的 JS 库

jquery - exports 未在 Typescript 中定义

Angular - 如何为可选输入属性设置默认值

javascript - Typescript:类型 'X' 与签名 '(prevState: undefined): undefined' 不匹配

angular - 在返回 observable 之前操作数据

javascript - visual studio typescript 与angular 2冲突