Skip to content

TypeScript 严格模式标准

严格模式选项

核心严格选项

选项默认推荐说明
strictfalsetrue启用所有严格检查
noImplicitAnyfalsetrue禁止隐式 any
strictNullChecksfalsetrue严格空值检查
strictFunctionTypesfalsetrue严格函数类型
strictBindCallApplyfalsetrue严格 bind/call/apply
strictPropertyInitializationfalsetrue严格属性初始化
noImplicitThisfalsetrue禁止隐式 this
alwaysStrictfalsetrue始终严格模式

额外质量选项

选项推荐说明
noUnusedLocalstrue未使用的局部变量
noUnusedParameterstrue未使用的参数
noImplicitReturnstrue隐式返回
noFallthroughCasesInSwitchtrueswitch 穿透
noUncheckedIndexedAccesstrue索引访问检查
exactOptionalPropertyTypestrue精确可选属性
noImplicitOverridetrue显式 override
noPropertyAccessFromIndexSignaturetrue索引签名访问

完整严格配置

json
{
  "compilerOptions": {
    /* 核心严格模式 */
    "strict": true,
    
    /* 额外严格检查 */
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    
    /* 一致性检查 */
    "forceConsistentCasingInFileNames": true,
    "allowUnreachableCode": false,
    "allowUnusedLabels": false
  }
}

渐进式迁移策略

阶段 1:基础(第 1 周)

json
{
  "compilerOptions": {
    "noImplicitAny": true,
    "strictNullChecks": false
  }
}

阶段 2:空值安全(第 2-3 周)

json
{
  "compilerOptions": {
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true
  }
}

阶段 3:完全严格(第 4 周)

json
{
  "compilerOptions": {
    "strict": true
  }
}

阶段 4:质量提升(第 5 周)

json
{
  "compilerOptions": {
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noUncheckedIndexedAccess": true
  }
}

常见错误处理

隐式 any

typescript
// ❌ 错误
function process(data) { }

// ✅ 修复
function process(data: unknown) { }

空值检查

typescript
// ❌ 错误
const value = obj.prop.nested;

// ✅ 修复
const value = obj?.prop?.nested;

索引访问

typescript
// ❌ 错误
const item = arr[index];

// ✅ 修复
const item = arr[index];
if (item !== undefined) {
  // 使用 item
}

记住:严格模式是 TypeScript 的精髓,逐步迁移比一次性启用更实际。

基于 MIT 许可发布