❓ 可选属性详解
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