打字稿:从联合接口类型获取独占成员
如何从联合打字稿中获取排他性成员?
How do I get the Exclusive Member from a Union Typescript?
selectedQueueItems: Array< TestA | TestB > = [];
TestA具有一个称为Food的接口成员,而TestB接口则没有.但是,其他大多数接口成员之间都是相似的.
TestA has an interface member called Food, that TestB interface does not have. However most of the other interface 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.
参考问题:
最简单的方法是让每个接口都具有一个公共属性,该属性对于联合中的每种类型都具有唯一的值.这是歧视的工会.
The easiest way to do this is to have each interface have a common property that has a unique value for each type in the union. This is a discriminated union.
可能看起来像这样:
interface TestA {
type: 'A'
Food: string
}
interface TestB {
type: 'B'
}
使用该设置,您可以测试item.type === 'A'
,然后打字稿知道您拥有TestA
类型的对象.
With that setup, you can test for item.type === 'A'
and then typescript knows that you have object of type TestA
.
可能看起来像这样:
for (const item of selectedQueueItems) {
if (item.type === 'A') {
// item is known to be a TestA in this scope, since only TestA has: .type === 'A'
console.log(item.Food) // Works
}
}
如果没有类似的属性,您仍然可以在通过'key' in object
检查访问它之前检查属性是否存在.
If there is no property like that, you can still check for the properties presence before you access it with a 'key' in object
check.
for (const item of selectedQueueItems) {
if ('Food' in item) {
// item is known to be a TestA in this scope, since only TestA has .Food
console.log(item.Food) // Works
}
}