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

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

问题描述

如何从联合打字稿中获取排他性成员?

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.

参考问题:

Typescript:从Union Class类型获取互斥成员

推荐答案

最简单的方法是让每个接口都具有一个公共属性,该属性对于联合中的每种类型都具有唯一的值.这是歧视的工会.

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
  }
}

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

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