对象是 可能地 '空' or 'undefined'
错误信息
对象是 可能地 '空'
快速摘要
使用 strictNullChecks 启用, TypeScript prevents 你从 accessing 属性 on 值那个能 是空 or undefined 不使用检查首先.
为什么发生
Accessing 属性 on 变量输入 as T | 空
Using 可选属性不使用检查 for undefined
函数返回 T | 空 and result 是 used 不使用空 检查
DOM 元素 lookup (getElementById) 返回 T | 空
最小示例
✗ 错误代码
function getName(user: { name: string } | null): string {
return user.name; // possibly null
}✓ 修复代码
function getName(user: { name: string } | null): string {
return user?.name ?? "unknown";
}Use 可选 chaining and nullish coalescing 到 safely handle 空.
如何诊断
检查如果变量是 输入使用 | 空 or | undefined
Look for 可选属性 (使用 ?) 那个能 是 undefined
检查如果值 comes 从函数那个能 返回空
如何修复
添加空 检查:
如果 (值 !== 空) { ... }Use 可选 chaining:
值?.属性Use nullish coalescing:
值 ?? defaultValueUse 非-空 assertion:
值!.属性(仅当 你're 确定)
如何预防
总是启用 strictNullChecks (部分的 strict 模式)
Use 可选 chaining and nullish coalescing for nullable 值
设计 APIs 到 avoid returning 空哪里可能