Skip to content

strictNullChecks:值可能为 null

快速摘要

你的变量类型为 T | null 但你将其当作 T 使用 —— TypeScript 在严格空值检查下阻止此操作。

为什么发生

  • 函数返回 T | null 但调用者未检查 null 就使用结果

  • 可选属性(prop?: T)在未先检查 undefined 的情况下被访问

  • DOM 查询如 document.getElementById 返回 HTMLElement | null 但被直接使用

最小示例

✗ 错误代码
function getElement(id: string) {
  const el = document.getElementById(id); // HTMLElement | null
  return el.innerHTML; // error: Object is possibly null
}
✓ 修复代码
function getElement(id: string) {
  const el = document.getElementById(id);
  return el?.innerHTML ?? ''; // safe access with fallback
}

使用可选链(?.)和空值合并(??)安全处理 null 情况,无需抑制类型检查。

如何诊断

  • 阅读 TS 错误:'Object is possibly null or undefined' 并注意变量和行号

  • 检查来源的类型签名 —— 返回类型是否包含 null 或 undefined?

  • 使用类型守卫(if (x !== null))在使用属性前收窄类型

如何修复

  • 在使用值前添加 null 检查:if (value !== null) { /* use value */ }

  • 仅在确定值不为 null 时使用非空断言操作符(!):value!.prop

  • 用空值合并运算符提供默认值:(value ?? defaultValue).prop

如何预防

  • 始终显式处理 null 和 undefined 情况 —— 不确定时不要用 ! 抑制错误

  • 对可能为 null 的值使用可选链(?.)安全访问属性:value?.prop

相关资源

相关课程

← 返回语言