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