第15章 可选属性与只读属性

案例15:用户档案接口 — 可选与只读属性

题目:设计一个用户档案(UserProfile)接口,其中 id 和 createdAt 为只读属性,email 和 nickname 为可选属性,其余为必填。要求展示:只读属性在初始化后不可修改、可选属性访问时的类型保护。
设计思路:使用 readonly 修饰 id 与 createdAt,使用 ? 标记 email 与 nickname。通过工厂函数创建对象,并尝试非法修改只读属性(编译报错),以及使用 if 判断可选属性是否存在,再进行安全访问。

🧩 核心代码

interface UserProfile {
  readonly id: number;
  readonly createdAt: string;
  name: string;
  age: number;
  email?: string;
  nickname?: string;
}

function createUser(id: number, name: string, age: number): UserProfile {
  return {
    id,
    createdAt: new Date().toISOString(),
    name,
    age,
  };
}

const user = createUser(1, "小明", 25);

// 尝试修改只读属性(编译报错)
// user.id = 100;

// 可选属性的类型保护
if (user.email) {
  console.log("邮箱:", user.email);
} else {
  console.log("未提供邮箱");
}

console.log("用户信息:", user);

运行结果

验证方法:运行代码后,控制台输出“未提供邮箱”和用户对象;尝试取消注释 user.id = 100 将触发 TypeScript 编译错误,说明只读属性被正确保护。
注意事项:readonly 仅保证编译期约束,运行时仍可能被修改;可选属性必须使用 严格空值检查(strictNullChecks) 才能发挥最大作用。

成功要点

掌握接口中可选与只读属性的写法,并理解在业务对象中合理使用二者,可提高类型安全性与代码可维护性。