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

如何在TypeScript中读取对象或其mutateMail子对象的值并保障类型安全

解决方案

1. 定义类型约束

首先基于你现有的ValuesType定义互斥的入参联合类型,从类型层面强制两种结构只能存在其一:

// 基础邮件值类型
interface ValuesType {
  contactId: string | undefined;
  from: string;
  to: string;
  cc: string;
  send?: boolean;
  id: string;
}

// sendMail 入参类型:两种合法结构互斥
type SendMailInput = 
  // 场景1:所有属性在根层级,不存在 mutateMail
  (ValuesType & { mutateMail?: never })
  // 场景2:属性都在 mutateMail 下,根层级无 ValuesType 对应属性
  | { mutateMail: ValuesType } & { [K in keyof ValuesType]?: never };

2. 实现 sendMail 函数

直接通过类型收窄获取最终的邮件对象,所有属性取值都有类型安全保障:

export const sendMail = (mail: SendMailInput): AppThunk => {
  // 类型自动收窄:不存在 mutateMail 时直接取根层级对象
  const targetMail = mail.mutateMail ?? mail;
  // 后续所有属性直接从 targetMail 取值即可,类型完全匹配 ValuesType
  const mailId = targetMail.id;
  const from = targetMail.from;
  const to = targetMail.to;
  const cc = targetMail.cc;
  // 你的邮件发送业务逻辑...
  console.log(mailId);
}

方案优势

  • 不需要拆分现有函数,完全兼容你现有的调用场景
  • 类型层面强校验:如果同时传入根层级属性和mutateMail,TS会直接抛出类型错误,避免非法入参
  • 不需要重复写三元判断,所有属性统一从targetMail取值,代码更简洁

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 09:15:03