开启 strictNullChecks 是 TypeScript 严格空值检查的核心,需在 tsconfig.json 中设 "strictNullChecks": true 或启用 "strict": true;命令行可用 tsc --strictNullChecks 临时启用;配合联合类型(如 string | null)、可选属性和参数确保检查生效,避免与 strict: false 冲突或滥用 any 和非空断言。

在 TypeScript 中开启严格的空值检查,核心是启用 strictNullChecks 编译选项。它不是“可选规则”,而是类型安全的基石——一旦开启,null 和 undefined 就不再能隐式赋值给其他类型(比如 string、number),必须显式声明联合类型(如 string | null)或使用可选属性(?)来表达可能为空的意图。
在 tsconfig.json 中启用 strictNullChecks
这是最标准、推荐的方式。打开项目根目录下的 tsconfig.json 文件,在 compilerOptions 中添加或确认以下配置:
"strictNullChecks": true- 更推荐直接启用整个严格模式:
"strict": true(它会自动包含strictNullChecks,以及noImplicitAny、strictFunctionTypes等关键检查)
示例片段:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"strict": true,
"skipLibCheck": true,
"esModuleInterop": true
}
}
命令行临时启用(调试用)
如果不想修改配置文件,可在编译时通过参数临时开启:
tsc --strictNullChecks- 或更完整:
tsc --strict
注意:这种方式只影响本次编译,不持久化,适合快速验证行为。
配合类型定义,让检查真正生效
光开启配置还不够。TypeScript 会根据你的类型声明做推断和校验。常见配合方式有:
- 对可能为空的变量,显式写联合类型:
let name: string | null = null; - 接口中可选属性自动推断为
T | undefined:interface User { email?: string; }→email类型即string | undefined - 函数参数若允许未传,用可选语法:
function log(msg?: string) { ... },此时msg类型为string | undefined
常见误配与注意事项
有些配置会削弱 strictNullChecks 的效果,需避免:
- 不要同时设置
"strict": false或"strictNullChecks": false—— 它们会直接关闭检查 - 避免滥用
any类型(如let data: any),它绕过所有类型检查,包括空值校验 - 注意
!.非空断言操作符(如user!.name)是绕过检查的“逃生舱”,仅在你 100% 确认非空时使用,否则可能掩盖真实问题











