strict 是 tsconfig 中的一个总开关,设为 true 会同时启用 noImplicitAny、strictNullChecks、strictFunctionTypes 等一系列检查规则。其中 strictNullChecks 影响最大:默认情况下 null 和 undefined 可以赋给任何类型,开启后它们变成独立类型,取值前必须先排除空值,从源头消灭空指针。
新项目建议第一时间打开 strict,早开早受益;老项目迁移则可以逐项开启各个子规则分步改造。严格模式短期会多写不少类型守卫与判空代码,但换来的是运行时几乎不再出现读 undefined 上的方法这类低级错误,团队协作时收益尤其明显。
// tsconfig.json // { // "compilerOptions": { "strict": true } // } function greet(name: string) { return 'hello ' + name; } const input: string | null = document.querySelector('#name')?.textContent; // strict 下不允许直接把 null 传给 string: greet(input ?? 'guest'); // OK // greet(input); // 报错:不能把 null 赋给 string