访问打字稿联合类型中的不同属性 [英] Accessing different properties in a typescript union type

查看:183
本文介绍了访问打字稿联合类型中的不同属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个处理数据库中对象的函数。我有两个不同的数据结构,其中相同的属性具有不同的名称。我无法改变它,所以我必须在JavaScript中处理它。

对象有其他差异,但这对这个函数并不重要。

我想用同样的东西两种不同类型的对象的功能。以下示例代码演示了我的问题:

I'm creating a function that handles objects from the database. I have two different data structures where the same property has a different name. I can't change that, so I have to handle it in JavaScript.
The objects have other differences, but that's not important to this function.
I want to use the same function for two different types of objects. Here's sample code demonstrating my problem:

interface TypeA {
    itemName: string;
}

interface TypeB {
    itemTitle: string;
}

function getItemName(item: TypeA | TypeB): string {
    let name = '';

    if (item.hasOwnProperty('itemName')) {
        name = item.itemName;
    } else {
        name = item.itemTitle;
    }

    return name;
}

当然,此代码运行。但是IDE将行 name = item.itemName; name = item.itemTitle; 标记为错误(类型)上不存在属性,因为两种类型都没有这两种属性。

Of course, this code runs. But the IDE marks both the lines name = item.itemName; and name = item.itemTitle; as errors ("Property does not exist on type"), because both types do not have both properties.

那么,这样做的正确打字方法是什么?

So, what's the proper typescript way to do this?

推荐答案

您需要创建一个User Defined Type Guard,然后您可以使用if语句并获得正确的输入。

You need to create a User Defined Type Guard, then you can use an if statement and get the correct typing.

function isTypeA(value: TypeA | TypeB): value is TypeA {
    return value.hasOwnProperty('itemName');
}

然后你可以让输入更清洁:

Then you can get the typing much cleaner:

function getItemName(item: TypeA | TypeB): string {
    return isTypeA(item) ? item.itemName : item.itemTitle;
}

检查出来此处。项目正确地转换为TypeA或TypeB。

Check it out here. Item is correctly cast to either TypeA or TypeB.

这篇关于访问打字稿联合类型中的不同属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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