🧪 Frontend Lab
交互式前端学习实验室

严格模式

typescript · intermediate · 10 min · Step 1/2

tsconfig.json strict

{
  "compilerOptions": {
    "strict": true  // 开启全部严格检查
  }
}

strict 包含的检查

选项效果
strictNullChecksnull/undefined 不能赋给其他类型
noImplicitAny不允许隐式 any
strictFunctionTypes函数参数类型严格检查
strictBindCallApplybind/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 的最大价值所在。