【问题标题】:How can I get the value of a property of type multiple union interface types?如何获取多个联合接口类型的属性的值?
【发布时间】:2020-10-02 13:22:10
【问题描述】:

我有以下代码:

  const arrayFromForm: IFirst[] | ISecond[] | IThird[]; // = ... it's initialized
  const arrayDB: IFirst[] | ISecond[] | IThird[]; // = ... it's initialized
  const entitiesFromDb = arrayDB.filter(
    (entity: IFirst | ISecond | IThird) =>
      !(arrayFromForm.map(({ id }) => id))
      .includes(entity.id)
  );

它给了我 1 个错误:"The map expression is not callable"

如果我错了,请纠正我,但我认为这是因为它不知道联合中的所有接口中都有一个名为id的属性。


我以前使用过类型保护,但我认为您只能在联合中的两种类型之间创建类型保护,因为您必须返回一个布尔值?

我想用 typescript(用户定义的类型保护、typeof、instanceof 等)解决这个问题,但我不确定这是否可行,不是吗? instanceof 不能为接口创建类型保护,对吧?
这里有什么好的解决方案?


编辑:我刚刚解决了一个接口的问题,该接口具有联合中的接口共有的属性,我只是用新接口更改了联合类型。这不是很好的解决方案,因为我想在类型联合中拥有的不同接口中使用特定的方法/属性。

所以我没有删除这个问题,因为了解是否存在用于类型联合的用户定义类型保护(其中包含超过 2 种类型)之类的东西仍然很有帮助。

【问题讨论】:

  • 在下面找到我的解决方案。

标签: angular typescript typeguards


【解决方案1】:

这似乎是 Typescript 中的一个已知问题。见Here

但现在你可以这样做:

const arrayFromForm: IFirst[] | ISecond[] | IThird[]; // = ... it's initialized
const entitiesFromDb = arrayDB.filter(
  (entity: IFirst | ISecond | IThird) =>
    !(arrayFromForm as {id: number}[]).map(item => item.id).includes(entity.id) // Pay attention to the brackets
);

我们将arrayFromForm 转换为一种适当的类型,而不是类型的联合。这接近您提出的解决方案,但我认为以这种方式维护它更容易。

【讨论】:

  • 感谢您的回复。这给了我以下错误:This filter expression is not callable. Each member of the union type has signatures, but none of those signatures are compatible with each other. 在第一个过滤器上:arrayDB.filter(...)
  • arrayDB 的类型是什么?
  • 非常感谢。我对数组应用了相同的逻辑并且它起作用了。 (arrayDB as {id: number}[])
【解决方案2】:

试试这个:-

const elementsIds = arrayFromForm.filter(arrItem => arrItem.id).map((item)=>item.id); 
  const entitiesFromDb = arrayDB.filter(
    (entity: IFirst | ISecond | IThird) =>
      !elementsIds.includes(entity.id)
  )

【讨论】:

  • 感谢您的回复。这给了我一个类似的错误:This filter expression is not callable. Each member of the union type has signatures, but none of those signatures are compatible with each other. 在第一个过滤器(第一行)
猜你喜欢
  • 2018-10-01
  • 2019-11-26
  • 1970-01-01
  • 2021-01-18
  • 1970-01-01
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多