可选属性
一句话解释
可选属性 (prop?: 类型) 是属性那个能 是 absent or undefined. 问题 mark 之前 colon marks 它 as 可选.
用大白话说
可选属性是 one 那个对象可能 or 可能不 有. 你 declare 它使用问题 mark: email?: string. TypeScript treats 它 as string | undefined — the property is either a string or not present.
Optional properties are useful for partial data, API responses with optional fields, and configuration objects where not all settings are required. They work with optional chaining (?.) for safe access.
The 部分<T> utility type makes all properties optional. The 必需<T> utility type makes all properties required (removes the ?).
示例
typescript
interface User {
name: string;
email?: string; // optional
}
const u1: User = { name: "Alice" }; // OK, email omitted
const u2: User = { name: "Bob", email: "b@x" }; // OK, email provided
console.log(u1.email?.toUpperCase()); // undefined (optional chaining)可选属性能 是 omitted. 可选 chaining safely accesses 它们.
相关术语
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。