联合类型上不存在 Typescript 属性 [英] Typescript property does not exist on union type

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

问题描述

这是我遇到过几次的情况,看起来应该相当简单,但是我找不到不将类型设置为 any 的解决方案

This is a situation I have ran into a couple of times, it seems like it should be fairly straightforward, but I can't find a solution that doesn't set the type to any

一个函数将两个不同的对象之一作为参数,检查接收到的对象,并返回相应的字段.

A function takes one of two different objects as the argument, checks which object has been received, and returns the corresponding field.

这是问题的简化版本,但问题是这两个对象只能通过它们的属性(没有重叠)来区分,而我无法访问任何属性,因为它们不存在在另一种类型.

This is a simplified version of the problem, but the issue is that the two objects are only distinguishable by their properties(which have no overlap), and I can't access any of the properties, because they're not present on the other type.

type Obj1 = {
  message: string
}

type Obj2 = {
  text: string
}

const getText = (obj: Obj1 |obj2): string => {
  if (obj.message) {
    return obj.message
  }

  return obj.text
}

推荐答案

你必须缩小类型.您可以使用 in 运算符.

You have to narrow down the type. You can do so by using the in operator.

const getText = (obj: Obj1 | Obj2): string => {
  if ("message" in obj) {
    return obj.message
  }

  return obj.text
}

这篇关于联合类型上不存在 Typescript 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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