You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React组件中如何从联合类型获取仅存在于单一类型的属性uid?

解决联合类型中获取非共有属性的问题

问题场景

React组件接收UserType或PersonType类型的参数,类型定义如下:

type PersonType = {
  name: string
  email: string 
  // 其他属性
}

type UserType = {
  uid: string
} & PersonType

function MyComponent(
  input: UserType | PersonType
) { 
  // 尝试获取uid时报错:Property 'uid' does not exist on type 'UserType | PersonType'
  // const uid = input.uid ?? undefined
}

需要实现:从input中获取uid属性,当属性不存在时返回undefined。

解决方案

1. 使用in操作符类型守卫

这是最直接的安全方式,通过in操作符判断属性是否存在,TypeScript会自动缩小当前变量的类型范围:

const uid = 'uid' in input ? input.uid : undefined;

2. 自定义类型谓词函数

如果需要在多处判断该类型,可封装成类型谓词函数提升复用性:

function isUser(input: UserType | PersonType): input is UserType {
  return 'uid' in input;
}

// 组件内使用
const uid = isUser(input) ? input.uid : undefined;

3. 类型断言结合可选链(谨慎使用)

若能确保业务逻辑不会出现异常,可通过类型断言快速实现,但这种方式会跳过TypeScript的类型检查,存在安全风险:

const uid = (input as UserType).uid ?? undefined;

原理说明

TypeScript对联合类型的属性访问有严格限制:仅允许访问所有联合类型成员共有的属性。由于PersonType没有uid属性,直接访问input.uid会触发类型错误。通过类型守卫可以让TypeScript识别当前input的具体类型,从而安全访问uid属性。

内容的提问来源于stack exchange,提问作者Luiz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 15:47:11