问题描述
如何从联合打字稿中获得独家会员?
selectedQueueItems: Array= [];
TestA 有一个名为 Food 的接口成员,而 TestB 接口没有.然而,大多数其他接口成员之间是相似的.
接收错误:
类型TestA"上不存在属性Food" |测试B'.
类型TestB"上不存在属性Food"
目前正在使用我们代码库中的现有设计.
参考问题:
最简单的方法是让每个接口都有一个公共属性,该属性对于联合中的每个类型都有唯一的值.这是一个歧视工会.
这可能看起来像:
interface TestA {类型:'A'食物:绳子}接口测试B{类型:'B'}
通过该设置,您可以测试 item.type === 'A'
然后打字稿知道您有 TestA
类型的对象.
可能看起来像这样:
for(selectedQueueItems 的常量项){if (item.type === 'A') {//item 在此范围内已知是 TestA,因为只有 TestA 具有: .type === 'A'console.log(item.Food)//有效}}
如果没有这样的属性,您仍然可以在使用'key' in object
检查访问它之前检查属性是否存在.
for(selectedQueueItems 的常量项){如果(项目中的食物"){//item 在这个范围内被称为 TestA,因为只有 TestA 有 .Foodconsole.log(item.Food)//有效}}
How do I get the Exclusive Member from a Union Typescript?
selectedQueueItems: Array< TestA | 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.
Receiving Error:
Currently working with existing design in our code base.
Reference question:
Typescript: Get Exclusive Members from Union Class Type
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.
That might look something like:
interface TestA {
type: 'A'
Food: string
}
interface TestB {
type: 'B'
}
With that setup, you can test for item.type === 'A'
and then typescript knows that you have object of type TestA
.
That might look like this:
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
}
}
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
}
}
这篇关于打字稿:从联合接口类型获取独占成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!