strict(严格模式,新项目无脑开)、 strict(严格模式,新项目无脑开)、 strict(严格模式,新项目无脑开)、
TypeScript 词条目录
前端Wiki/TypeScript/实战/工程配置

tsconfig 常用配置

tsconfig.json 是编译器配置总开关。核心字段:strict(严格模式,新项目无脑开)、target(JS 版本降级)、module(模块方案)、outDir(产物目录)、include/exclude(编译范围)。

strict 打开后会连带启用 noImplicitAny、strictNullChecks、strictFunctionTypes 等一整套严格检查。strictNullChecks 是其中影响最大的:null/undefined 不再能乱赋,强制你处理空值(用 ?? 或非空断言 !)。

  • strict: true = 一整套严格检查套餐,新项目无脑开
  • strictNullChecks:null/undefined 变成独立类型,必须显式处理
  • moduleResolution:node16/bundler 决定 import 路径怎么解析
TS
// tsconfig.json(常见前后端通用配置)
{
  "compilerOptions": {
    "target": "ES2022",            // 编译到哪个 JS 版本
    "module": "ESNext",            // 输出模块格式
    "moduleResolution": "bundler", // 解析策略(Vite/webpack 用 bundler)
    "strict": true,                // 严格模式总开关
    "noEmit": true,                // 只做类型检查,产物由打包器生成
    "esModuleInterop": true,       // 允许 default 导入方式引入 CJS
    "skipLibCheck": true,          // 跳过 node_modules 内类型检查
    "lib": ["ES2022", "DOM"],      // 可用的运行时 API 类型
    "outDir": "dist",              // 产物目录
    "include": ["src"]             // 编译范围
  }
}
JS
// strict 开启后最常见的"空值处理"改造:
// 关闭时能跑,开启后 location.length 报错(可能是 null)
function cityLength(location) {
  // TS 要求处理 null,运行时也更安全
  return (location ?? '').length;
}
console.log(cityLength('北京'));    // 2
console.log(cityLength(null));      // 0,而不是 TypeError
本节要点strict 无脑开;strictNullChecks 强迫处理空值;noEmit + bundler 是现代前端标配。