在 TypeScript 中,可选链(Optional Chaining)、空值合并(Nullish Coalescing)和非空断言(Non-null Assertion)是处理 null
/undefined
的重要语法。以下是详细解释:
作用:安全访问嵌套对象的属性或方法,避免因中间值为 null
/undefined
而抛出错误。
const result = obj?.prop?.nestedProp?.method?.();
- 如果
obj
、prop
、nestedProp
或method
为null
/undefined
,整个表达式返回undefined
。 - 如果所有中间值存在,则正常执行。
// 安全访问属性
const name = user?.profile?.name; // 如果 user 或 profile 是 null/undefined,返回 undefined
// 安全调用方法
user?.updateProfile?.(); // 如果 updateProfile 不存在,不执行
// 安全访问数组
const item = arr?.[0]; // 如果 arr 是 null/undefined,返回 undefined
作用:当左侧值为 null
或 undefined
时,返回右侧的默认值。
const value = input ?? defaultValue;
- 仅在左侧是
null
/undefined
时使用右侧默认值。 - 对比
||
(逻辑或)的区别:||
会对所有假值(0
、""
、false
、NaN
)生效。
const age = 0;
console.log(age ?? 18); // 0(因为左侧不是 null/undefined)
console.log(age || 18); // 18(因为 0 是假值)
作用:明确告诉 TypeScript,某个值一定不是 null
/undefined
(需开发者自己确保安全性)。
const value = obj!.prop!.nestedProp;
- 跳过 TypeScript 的类型检查,强制认为值存在。
- 如果实际运行时值为
null
/undefined
,会抛出错误!
// 假设 user 是从外部获取的,开发者明确知道它非空
const name = user!.name;
// 非空断言数组
const items = data!.results!.map(...);
作用:将任意值转换为布尔值(true
/false
)。
const hasValue = !!value;
- 等价于
Boolean(value)
。 - 对假值(
0
、""
、null
、undefined
、false
、NaN
)返回false
,其他返回true
。
console.log(!!0); // false
console.log(!!"hello"); // true
console.log(!!null); // false
语法 | 作用 | 适用场景 |
---|---|---|
a?.b |
安全访问嵌套属性/方法 | 不确定中间值是否存在时 |
a ?? b |
默认值(仅对 null /undefined 生效) |
需要区分 0 、"" 和 null /undefined |
a! |
断言值非空(跳过类型检查) | 开发者明确知道值非空时 |
!!a |
强制转换为布尔值 | 需要明确的 true /false 判断 |
// 安全访问 + 默认值
const name = user?.profile?.name ?? "Anonymous";
// 非空断言 + 可选链
const length = data!.results?.length ?? 0;
- 滥用
!
的风险:如果实际值为null
/undefined
,会导致运行时错误。 - 与
||
的区别:??
仅处理null
/undefined
,而||
处理所有假值。 - 可选链的性能:
a?.b
等价于a == null ? undefined : a.b
,无副作用。
合理使用这些语法能显著提升代码的健壮性和可读性!