typescript 中的可选链、非空断言操作符和空值合并操作符

在 TypeScript 中,有几个操作符在处理可能为 nullundefined 的值时非常有用,它们分别是可选链操作符(Optional Chaining Operator)、非空断言操作符(Non-null Assertion Operator)和空值合并操作符(Nullish Coalescing Operator)。下面是这些操作符的详细解释和示例:

1. 可选链操作符(Optional Chaining Operator)

可选链操作符 ?. 允许你安全地访问嵌套对象的属性,即使某些属性可能是 nullundefined。如果链中的某个部分是 nullundefined,表达式的结果立即返回 undefined,而不是抛出错误。

示例

typescript 复制代码
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 编译器某个值一定不是 nullundefined。这在你确信某个值不为空但 TypeScript 无法推断出来的情况下非常有用。

注意: 滥用非空断言操作符可能会导致运行时错误,因此应谨慎使用。

示例

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)

空值合并操作符 ?? 用于为可能为 nullundefined 的表达式提供一个默认值。与逻辑或操作符 || 不同,?? 只在左侧表达式为 nullundefined 时才返回右侧表达式。

示例

typescript 复制代码
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 值时返回右侧表达式

总结

  • 可选链操作符 (?.):安全地访问嵌套对象属性,防止 nullundefined 导致的错误。
  • 非空断言操作符 (!):告诉 TypeScript 某个值一定不为 nullundefined,但应谨慎使用。
  • 空值合并操作符 (??):在左侧表达式为 nullundefined 时提供一个默认值,与逻辑或操作符 || 不同,它只关注 nullundefined

这些操作符可以大大提高代码的健壮性和可读性,尤其是在处理可能为 nullundefined 的值时。

相关推荐
utf8mb4安全女神8 分钟前
【rsyslog服务】把所有服务的“临界点”以上的错误都保存在/var/log/alert.log⽇志中
java·前端·javascript
csdn_aspnet25 分钟前
javascript 算法 LeetCode 编号 70 - 爬楼梯
开发语言·javascript·算法·leetcode·ecmascript
swipe25 分钟前
DeepAgents 多 Agent 深度调研助手工程实战:从 createDeepAgent 到可控调研工作流
javascript·面试·langchain
moMo1 小时前
JavaScript 变量提升,执行上下文里的各种门道
javascript·面试
weixin_471383031 小时前
由浅入深递归练习
前端·javascript·vue.js
丷丩1 小时前
MapLibre GL JS第21课:绘制GeoJSON点图标、注记
前端·javascript·gis·mapbox·maplibre gl js
丷丩2 小时前
MapLibre GL JS第20课:更新GeoJSON多边形
前端·javascript·gis·mapbox·maplibre gl js
丷丩2 小时前
MapLibre GL JS第33课:渲染世界副本
javascript·gis·map·mapbox·maplibre gl js
bonechips2 小时前
深入理解 JavaScript的历史包袱——变量提升(Hoisting)
javascript·深度学习
丷丩3 小时前
MapLibre GL JS第31课:添加实时数据
javascript·gis·map·mapbox·maplibre gl js