在 TypeScript 中,有几个操作符在处理可能为 null 或 undefined 的值时非常有用,它们分别是可选链操作符(Optional Chaining Operator)、非空断言操作符(Non-null Assertion Operator)和空值合并操作符(Nullish Coalescing Operator)。下面是这些操作符的详细解释和示例:
1. 可选链操作符(Optional Chaining Operator)
可选链操作符 ?. 允许你安全地访问嵌套对象的属性,即使某些属性可能是 null 或 undefined。如果链中的某个部分是 null 或 undefined,表达式的结果立即返回 undefined,而不是抛出错误。
示例:
interface User {
name?: string;
address?: {
city?: string;
};
}
const user: User = {
name: "John",
address: null
};
const city = user.address?.city; // 结果为 undefined,而不是抛出错误2. 非空断言操作符(Non-null Assertion Operator)
非空断言操作符 ! 用于告诉 TypeScript 编译器某个值一定不是 null 或 undefined。这在你确信某个值不为空但 TypeScript 无法推断出来的情况下非常有用。
注意: 滥用非空断言操作符可能会导致运行时错误,因此应谨慎使用。
示例:
function getName(user: { name?: string }) {
return user.name!; // 使用非空断言操作符,告诉 TypeScript user.name 一定不为 null/undefined
}
// 使用示例
const user = { name: "Alice" };
console.log(getName(user)); // 输出 "Alice"3. 空值合并操作符(Nullish Coalescing Operator)
空值合并操作符 ?? 用于为可能为 null 或 undefined 的表达式提供一个默认值。与逻辑或操作符 || 不同,?? 只在左侧表达式为 null 或 undefined 时才返回右侧表达式。
示例:
const message = null ?? "Default message"; // 结果为 "Default message"
const value = 0 ?? "Default value"; // 结果为 0,因为 0 不是 null 或 undefined
// 另一个示例
const userInput = "";
const displayedMessage = userInput ?? "No input provided"; // 结果为 "",因为 "" 是空字符串,但不是 null 或 undefined
const fallbackMessage = userInput || "No input provided"; // 结果为 "No input provided",因为 || 会在左侧表达式为 falsy 值时返回右侧表达式总结
- 可选链操作符 (
?.):安全地访问嵌套对象属性,防止null或undefined导致的错误。 - 非空断言操作符 (
!):告诉 TypeScript 某个值一定不为null或undefined,但应谨慎使用。 - 空值合并操作符 (
??):在左侧表达式为null或undefined时提供一个默认值,与逻辑或操作符||不同,它只关注null和undefined。
这些操作符可以大大提高代码的健壮性和可读性,尤其是在处理可能为 null 或 undefined 的值时。










