打字稿:从联合类类型中获取独占成员 [英] Typescript: Get Exclusive Members from Union Class Type

查看:37
本文介绍了打字稿:从联合类类型中获取独占成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从联合打字稿中获得独家会员?

selectedQueueItems: Array<测试A |测试B>= [];

TestA 有一个名为 Food 的类成员,而 TestB 没有.然而,大多数其他班级成员彼此相似.

接收错误:

<块引用>

类型TestA"上不存在属性Food" |测试B'.

<块引用>

类型TestB"上不存在属性Food"

目前正在使用我们代码库中的现有设计.

解决方案

您需要进行运行时检查以确保您调用的方法存在.

在这种情况下,您将检查每个对象是否是您知道具有 Food 成员的类的实例:

for(selectedQueueItems 的常量项){如果(TestA 的项目实例){控制台.日志(项目.食物)}}

如果对象是使用 new TestA() 或 new TestB() 创建的,那么这将正常工作.如果您以其他方式创建这些对象,那么您需要以不同的方式对其进行测试.这实际上取决于这些对象是什么以及您如何构建它们.但它可能涉及歧视工会.

How do I get the Exclusive Member from a Union Typescript?

selectedQueueItems: Array< TestA | TestB > = [];

TestA has a class member called Food, that TestB does not have. However most of the other class members are similar between each.

Receiving Error:

Property 'Food' does not exist on type 'TestA | TestB'.

Property 'Food' does not exist on type 'TestB'

Currently working with existing design in our code base.

解决方案

You'd need a runtime check to ensure the method you are calling exists.

In this case, you would check to see if each object is an instance of the class that you know has a Food member:

for (const item of selectedQueueItems) {
  if (item instanceof TestA) {
    console.log(item.Food)
  }
}

If the objects are created with new TestA() or new TestB() then this will work fine. If you are creating those object other ways, then you would need to test that in different ways. That really depends on what those objects are and how you build them. But it may involve discriminated unions.

这篇关于打字稿:从联合类类型中获取独占成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆