Skip to content

Files

Latest commit

 

History

History
123 lines (91 loc) · 3.85 KB

可选链.md

File metadata and controls

123 lines (91 loc) · 3.85 KB

TypeScript 可选链、空值合并和非空断言

在 TypeScript 中,可选链(Optional Chaining)、空值合并(Nullish Coalescing)和非空断言(Non-null Assertion)是处理 null/undefined 的重要语法。以下是详细解释:


1. 可选链 ?.(Optional Chaining)

作用:安全访问嵌套对象的属性或方法,避免因中间值为 null/undefined 而抛出错误。

语法示例:

const result = obj?.prop?.nestedProp?.method?.();

行为:

  • 如果 objpropnestedPropmethodnull/undefined,整个表达式返回 undefined
  • 如果所有中间值存在,则正常执行。

常见场景:

// 安全访问属性
const name = user?.profile?.name; // 如果 user 或 profile 是 null/undefined,返回 undefined

// 安全调用方法
user?.updateProfile?.(); // 如果 updateProfile 不存在,不执行

// 安全访问数组
const item = arr?.[0]; // 如果 arr 是 null/undefined,返回 undefined

2. 空值合并 ??(Nullish Coalescing)

作用:当左侧值为 nullundefined 时,返回右侧的默认值。

语法示例:

const value = input ?? defaultValue;

行为:

  • 仅在左侧是 null/undefined 时使用右侧默认值。
  • 对比 ||(逻辑或)的区别:|| 会对所有假值(0""falseNaN)生效。

示例:

const age = 0;
console.log(age ?? 18); // 0(因为左侧不是 null/undefined)
console.log(age || 18); // 18(因为 0 是假值)

3. 非空断言 !(Non-null Assertion)

作用:明确告诉 TypeScript,某个值一定不是 null/undefined(需开发者自己确保安全性)。

语法示例:

const value = obj!.prop!.nestedProp;

行为:

  • 跳过 TypeScript 的类型检查,强制认为值存在。
  • 如果实际运行时值为 null/undefined,会抛出错误!

示例:

// 假设 user 是从外部获取的,开发者明确知道它非空
const name = user!.name;

// 非空断言数组
const items = data!.results!.map(...);

4. 双非断言 !!(Double Negation)

作用:将任意值转换为布尔值(true/false)。

语法示例:

const hasValue = !!value;

行为:

  • 等价于 Boolean(value)
  • 对假值(0""nullundefinedfalseNaN)返回 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;

注意事项

  1. 滥用 ! 的风险:如果实际值为 null/undefined,会导致运行时错误。
  2. || 的区别?? 仅处理 null/undefined,而 || 处理所有假值。
  3. 可选链的性能a?.b 等价于 a == null ? undefined : a.b,无副作用。

合理使用这些语法能显著提升代码的健壮性和可读性!