Skip to content

可选 Chaining

一句话解释

可选 chaining (?.) safely accesses nested 属性, returning undefined 相反的 throwing 当左 边是 空 or undefined.

用大白话说

可选 chaining (?.) is a shorthand for safe property access. If the left side is null or undefined, it short-circuits and returns undefined instead of throwing a TypeError. This avoids the need for explicit null checks.

For example, 用户?.地址?.city returns undefined if user is null or if user.address is null, instead of throwing. Without optional chaining, you'd need 用户 && 用户.地址 && 用户.地址.city.

Optional chaining also works with method calls (obj?.方法()) and bracket access (arr?.[0]). It is available in TypeScript 3.7+ and is now standard JavaScript (ES2020).

示例

typescript
interface User { profile?: { name?: string; }; }
const user: User = {};

// Without optional chaining
const name1 = user && user.profile && user.profile.name; // undefined

// With optional chaining
const name2 = user?.profile?.name; // undefined (much cleaner)

可选 chaining 短-circuits 到 undefined 相反的 throwing on 空/undefined.

相关术语

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表