tsconfig 严格模式配置
掌握 tsconfig.json 中的 strict 标志及其子选项,提升类型安全性。 · 难度:入门 · +15XP
tsconfig 严格模式配置
严格模式通过启用一系列类型检查选项来减少潜在错误。核心是设置 strict: true,它会开启 noImplicitAny、strictNullChecks、strictFunctionTypes、strictBindCallApply 等子选项。推荐在新项目中默认启用,以捕获更多类型错误。
// tsconfig.json
{
"compilerOptions": {
"strict": true,
// 等价于以下所有选项为 true:
// "noImplicitAny": true,
// "strictNullChecks": true,
// "strictFunctionTypes": true,
// "strictBindCallApply": true,
// "strictPropertyInitialization": true,
// "noImplicitThis": true,
// "alwaysStrict": true
}
}
// 严格模式下的常见错误
let name: string;
name = null; // 错误:不能将 null 赋值给 string