← 返回完整题库
Typescript困难

如何检查TypeScript中的null和undefined ?

参考答案

严格模式下的两种值

  • null:显式的"空值",typeof null === 'object'(历史遗留)。
  • undefined:未赋值/不存在的值,typeof undefined === 'undefined'。

开启 strictNullChecks 后,null 与 undefined 不再属于所有类型的子类型,必须显式声明包含它们,这正是"检查"的核心。

检查方式

  1. 直接判断
if (value === null || value === undefined) { /* ... */ }
if (value == null) { /* 同时覆盖 null 与 undefined,推荐 */ }
  1. 可选链 + 空值合并
const name = user?.profile?.name ?? '默认';
  1. 类型守卫收窄
function isDefined<T>(v: T | null | undefined): v is T {
  return v !== null && v !== undefined;
}
if (isDefined(x)) x.toFixed();   // ✅
  1. 非空断言(你确信不为空时)
document.getElementById('app')!.innerHTML = '';
  1. 控制流分析:TS 会在 if 分支内自动收窄,throw 之后的代码也被认为已排除空值。
  2. **NonNullable<T>** 从类型层面去掉 null | undefined:
type Safe = NonNullable<string | null | undefined>;  // string

工程配置

  • "strictNullChecks": true(strict 已包含)。
  • "noUncheckedIndexedAccess": true:索引访问结果自动加 | undefined。
  • "exactOptionalPropertyTypes": true:区分"属性缺失"与"属性值为 undefined"。

注意

  • typeof null === 'object',用 typeof 判空必须写 === null,不能用 !value(会误伤 0、'')。
  • ?. 只在访问/调用时短路,不会让后续运算跳过;要用 ?? 给默认值。
  • 非空断言不会做运行时检查,滥用会把 bug 藏到线上。

本题来自 计算机知识面试题库,共 921 道题。