tsconfig.json strict
{
"compilerOptions": {
"strict": true // 开启全部严格检查
}
}
strict 包含的检查
| 选项 | 效果 |
|---|
| strictNullChecks | null/undefined 不能赋给其他类型 |
| noImplicitAny | 不允许隐式 any |
| strictFunctionTypes | 函数参数类型严格检查 |
| strictBindCallApply | bind/call/apply 类型安全 |
| strictPropertyInitialization | 类属性必须初始化 |
strictNullChecks 示例
// 关闭时
const el = document.getElementById('app');
el.innerHTML = 'Hello'; // OK(但可能是 null!)
// 开启时
const el = document.getElementById('app');
el.innerHTML = 'Hello'; // ❌ el 可能为 null
// 正确写法
const el = document.getElementById('app');
if (el) el.innerHTML = 'Hello'; // ✅
始终开启 strict 模式,这是 TypeScript 的最大价值所在。