🎯 学习目标

  • 深入理解可选属性的使用场景
  • 掌握只读属性的定义和限制
  • 学会正确使用可选链操作符
  • 了解 Readonly 工具类型

可选属性详解

interface User { id: number; name: string; email?: string; // 可选属性 phone?: string; // 可选属性 address?: { // 可选的嵌套对象 city: string; street: string; }; } // 创建对象时可选属性可以不提供 const user1: User = { id: 1, name: 'Alice' }; const user2: User = { id: 2, name: 'Bob', email: 'bob@example.com', address: { city: 'Beijing', street: 'Main Street' } };

🔗 可选链操作符

interface User { id: number; name: string; address?: { city?: string; zip?: string; }; } const user: User = { id: 1, name: 'Alice' }; // 使用可选链安全访问嵌套属性 const city = user.address?.city; // undefined const zip = user.address?.zip; // undefined // 空值合并提供默认值 const cityName = user.address?.city ?? '未知城市'; // 可选链调用方法 interface Config { logger?: { log?: (msg: string) => void; }; } const config: Config = {}; config.logger?.log?.('Hello'); // 安全调用,不会报错
💡
可选链

?. 操作符会在属性为 null 或 undefined 时短路返回 undefined,避免运行时错误。

🔒 只读属性

interface Config { readonly apiUrl: string; readonly apiKey: string; timeout?: number; // 可选 + 非只读 } const config: Config = { apiUrl: 'https://api.example.com', apiKey: 'secret-key', timeout: 5000 }; // 无法修改只读属性 config.apiUrl = 'https://new.api.com'; // Error config.apiKey = 'new-key'; // Error // 非只读属性可以修改 config.timeout = 10000; // OK

Readonly 工具类型

interface User { id: number; name: string; email: string; } // 使用 Readonly 使所有属性变为只读 type ReadonlyUser = Readonly<User>; const user: ReadonlyUser = { id: 1, name: 'Alice', email: 'alice@example.com' }; user.name = 'Bob'; // Error: 所有属性都只读 // ReadonlyArray const numbers: ReadonlyArray<number> = [1, 2, 3]; numbers.push(4); // Error numbers[0] = 10; // Error

📝 本节小结

  • • ? 定义可选属性,创建对象时可省略
  • • readonly 定义只读属性,创建后不可修改
  • • 使用 ?. 安全访问可能为空的属性
  • • Readonly<T> 使所有属性变为只读