可选 Chaining in TypeScript
Safely access nested 属性使用 ?. 运算符不使用运行时错误.
你将学到
- 如何 ?. 运算符短-circuits on 空 and undefined
- 可选方法 calls and 可选元素 access
- 组合可选 chaining 使用 nullish coalescing
- 当可选 chaining 返回 undefined 对比 throwing
概念讲解
The ?. Operator
Optional chaining (?.) lets you safely access nested properties without manually checking each level for null. Instead of 用户 && 用户.profile && 用户.profile.name, you write 用户?.profile?.name. If any link in the chain is 空 or undefined, the entire expression short-circuits and returns undefined — no runtime error. This operator was added in TypeScript 3.7 and is now standard in modern JavaScript.
Three Forms of ?.
Optional chaining has three forms: property access (obj?.prop), method call (obj?.方法()), and element access (arr?.[索引]). The method call form is especially useful for optional callbacks: onComplete?.(result) calls the callback if it exists, otherwise does nothing. All three forms short-circuit to undefined when the left side is null or undefined.
Combining with ??
Optional chaining returns undefined when it short-circuits, which you often want to replace with a default value. The nullish coalescing operator (??) is the perfect partner: 用户?.name ?? "Anonymous" returns the name if it exists, or "Anonymous" if the chain short-circuits. This combination handles the entire "deeply nested, 可能地 missing, 使用默认" pattern in one readable expression.
示例代码
// Nested data that may be partially missing.
interface User {
profile?: {
name?: string;
address?: {
city?: string;
};
};
}
// Without optional chaining — verbose and error-prone.
function getCityOld(user: User): string | undefined {
if (user.profile && user.profile.address) {
return user.profile.address.city;
}
return undefined;
}
// With optional chaining — clean and safe.
function getCity(user: User): string | undefined {
return user?.profile?.address?.city;
}
// Optional method call — invokes only if defined.
let callback: ((msg: string) => void) | undefined;
callback?.("done"); // no error if callback is undefined
// Combining ?. with ?? for a default value.
function getDisplayName(user: User): string {
return user?.profile?.name ?? "Anonymous";
}
const user: User = { profile: { address: { city: "Paris" } } };
console.log(getCity(user)); // "Paris"
console.log(getDisplayName({})); // "Anonymous"
?. 运算符短-circuits 到 undefined 当任何部分的 链是 空/undefined. Use 它 for 属性 access, 方法 calls, and 元素 access. Pair 使用 ?? for defaults.
动手试一试
- JSON Formatter
格式 nested JSON 到 visualize 链可选 chaining traverses.
- JSON Path
JSONPath 查询 mirror 可选 chaining for deep JSON access.
常见错误
错误写法
Using 可选 chaining on 值那个是 从不空
正确做法
如果类型 guarantees 属性 exists, ?. 添加不必要 overhead and hides 类型错误. 仅 use ?. 哪里类型 actually 包含空 or undefined.
错误写法
Confusing 可选 chaining (?.) 使用非-空 assertion (!.)
正确做法
?. 返回 undefined 如果值 是空 (safe). !. asserts 非-空 and throws 如果它 是空 (unsafe). Use ?. for safety, !. 仅使用 proof 的非-空.
练习 可选 Chaining in TypeScript
4 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。