第58章 可选链

案例58:可选链 — 安全访问嵌套对象属性

题目:开发一个用户信息展示函数,当用户数据深层嵌套缺失时(如缺少地址或联系方式),不抛异常,优雅返回默认文案。

设计思路

利用TypeScript的可选链(?.)与空值合并(??),逐层安全访问对象属性。配合类型守卫接口,明确数据结构,避免任何运行时崩溃。

核心代码

interface User {
  name: string;
  address?: {
    city?: string;
    zip?: string;
  };
  contact?: {
    email?: string;
    phone?: string;
  };
}

function displayUser(user: User): string {
  const city = user.address?.city ?? "未知城市";
  const zip = user.address?.zip ?? "无邮编";
  const email = user.contact?.email ?? "未留邮箱";
  const phone = user.contact?.phone ?? "未留电话";
  return `用户: ${user.name} | 城市: ${city} | 邮编: ${zip} | 邮箱: ${email} | 电话: ${phone}`;
}

// 测试
const u1: User = { name: "张三", address: { city: "北京" }, contact: { phone: "1380000" } };
const u2: User = { name: "李四" };
console.log(displayUser(u1));
console.log(displayUser(u2));

运行结果(确认输出)

用户: 张三 | 城市: 北京 | 邮编: 无邮编 | 邮箱: 未留邮箱 | 电话: 1380000

用户: 李四 | 城市: 未知城市 | 邮编: 无邮编 | 邮箱: 未留邮箱 | 电话: 未留电话

提示:可选链只在对象为 null 或 undefined 时短路,普通空字符串和0不会被跳过。

注意:可选链不能用于赋值左侧(如 user.address?.city = "x"),语法非法。

成功要点:结合 ?? 提供默认值,是处理API返回数据最稳健的方式之一。

验证方法

在TypeScript Playground或本地工程运行,执行 tsc && node 后观察两行输出。可自行添加 address: null 测试,验证不崩溃。

注意事项

嵌套超过3层时,可读性下降,建议适当拆分函数或使用lodash的 get,但原生方案已满足多数场景。