打字稿:从工会班级类型中获得独家成员 [英] Typescript: Get Exclusive Members from Union Class Type
问题描述
如何从联合打字稿中获取排他性成员?
How do I get the Exclusive Member from a Union Typescript?
selectedQueueItems: Array< TestA | TestB > = [];
TestA有一个叫做Food的类成员,而TestB没有.但是,其他大多数班级成员之间都是相似的.
TestA has a class member called Food, that TestB does not have. However most of the other class members are similar between each.
接收错误:
"TestA |类型"上不存在食品"属性TestB'.
Property 'Food' does not exist on type 'TestA | TestB'.
类型"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.
在这种情况下,您将检查每个对象是否是您知道具有Food
成员的类的实例:
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)
}
}
如果使用new TestA()
或新的TestB()
创建对象,则可以正常工作.如果要以其他方式创建这些对象,则需要以其他方式进行测试.这实际上取决于这些对象是什么以及如何构建它们.但这可能涉及歧视的工会.
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屋!