TypeScript 工程配置:tsconfig 怎样决定检查严格程度和模块解析
版本:TypeScript 7.0.2(当前 npm latest),对照 6.0.3;Node.js 22.23.5。strict 相关的内部逻辑取自 typescript@6.0.3 的 lib/typescript.js。
概念
tsconfig.json 描述两件事:编译哪些文件(files、include、exclude),以及怎样编译(compilerOptions)。compilerOptions 按作用对象可以分成四类:
| 类别 | 代表选项 | 影响 |
|---|---|---|
| 检查严格程度 | strict 及其子开关、noUncheckedIndexedAccess、exactOptionalPropertyTypes | 检查器对同一段代码报不报错 |
| 模块与解析 | module、moduleResolution、verbatimModuleSyntax、isolatedModules | 一条 import 找到哪个文件、输出成什么模块格式、类型导入如何删除 |
| 生成 | target、outDir、rootDir、sourceMap、noEmit、noEmitOnError、declaration | 输出什么 JavaScript、放在哪里 |
| 环境声明 | lib、types、skipLibCheck | 哪些全局 API 有类型可用、声明文件要不要检查 |
声明文件 .d.ts 只含类型,不生成 JavaScript。来源有三种:TypeScript 自带的 lib.*.d.ts(由 lib 和 target 选择),npm 包自带或 @types/包名 提供的声明,以及项目里手写的声明。.tsx 是可以包含 JSX 的 TypeScript 源文件。
底层机制
strict 是一组开关的默认值
strict 本身不对应任何检查。检查器读取某个严格子开关时调用 getStrictOptionValue,逻辑是:
1
compilerOptions[flag] === undefined ? compilerOptions.strict !== false : !!compilerOptions[flag]
即子开关显式写了就用它的值,没写就跟随 strict。在 6.0.3 的选项表中带 strictFlag: true 的有八个:noImplicitAny、noImplicitThis、strictNullChecks、strictFunctionTypes、strictBindCallApply、strictPropertyInitialization、strictBuiltinIteratorReturn、useUnknownInCatchVariables,此外 alwaysStrict 也受 strict 控制。注意表达式里的 strict !== false:strict 没写时视为开启,这是 6.0 改变默认值的实现方式。
noUncheckedIndexedAccess 和 exactOptionalPropertyTypes 不在这组里,strict: true 不会打开它们(实验 1)。
6.0 和 7.0 改了什么
TypeScript 6.0 是最后一个用 JavaScript 实现的版本,7.0 是用 Go 重写的原生编译器。本文的严格检查、verbatimModuleSyntax、nodenext、types 默认值几项实验在两个版本下都运行过,除弃用选项外报错相同。
两个版本的配置变化分两步:6.0 改变了一批默认值,并把一批旧选项标为弃用;7.0 直接删除这些弃用选项。默认值的变化如下:
| 选项 | 6.0 之前的默认 | 6.0 起的默认 |
|---|---|---|
strict | false | true |
module | 随 target 变化 | esnext |
target | es5 | 当前最新的 ECMAScript 版本(现为 es2025) |
types | 自动包含 node_modules/@types 下的全部包 | [] |
rootDir | 从输入文件推断公共目录 | tsconfig.json 所在目录 |
noUncheckedSideEffectImports | false | true |
弃用(6.0 报错,可用 "ignoreDeprecations": "6.0" 暂时屏蔽)并在 7.0 删除的选项包括 target: es5、moduleResolution: node(即 node10)和 classic、baseUrl、outFile、module: amd/umd/systemjs/none、esModuleInterop: false 等。实验 2 是同一份旧配置在两个版本下的报错。
types 的变化影响最大。types 控制哪些 @types 包的全局声明自动加入编译。以前 @types/node、@types/jest 装上就生效,process、describe 随处可用;现在默认一个都不加,需要显式写 "types": ["node"]。显式 import 的模块不受这个字段影响,它们按模块解析找声明。
模块解析:编译期找文件,运行期另找一次
moduleResolution 决定检查器如何把 import "./model.js" 映射到一个源文件或声明文件。它只影响编译期,生成的 JavaScript 保留原来的导入字符串(除非开启 TypeScript 5.7 起的 rewriteRelativeImportExtensions)。运行时由浏览器、Node.js 或打包工具按各自规则再解析一次。
| 设置 | 相对导入的规则 | 对应的运行环境 |
|---|---|---|
nodenext / node16 | ESM 文件中相对导入必须写扩展名,按 package.json 的 type、exports 判断格式 | Node.js |
bundler | 允许省略扩展名,支持 exports | Vite、Webpack 等打包工具 |
写 .js 而不是 .ts,是因为运行时加载的是编译后的 .js 文件;检查器在解析时会把 ./model.js 对应到同目录的 model.ts。bundler 允许 import "./label",是因为打包工具会补全扩展名;把同样的代码直接交给 Node.js 或浏览器原生 ESM,就会找不到模块(实验 3)。
声明文件的查找与 skipLibCheck
导入一个包时,检查器依次查找包自带的声明(package.json 的 types/exports)、@types/包名,都找不到但存在 JS 文件时报 TS7016,并把这个模块视为 any。手写 declare module "包名" { ... } 可以补上声明;只写 declare module "包名";(简写形式)则模块中的一切都是 any。
声明文件的内容由编写者负责,检查器无法核对它与 JS 实现是否一致:声明了不存在的函数,编译照样通过(实验 3)。
skipLibCheck 跳过对所有 .d.ts 文件自身的检查,只检查源码用到的部分。lib.dom.d.ts 这类大文件里的每个声明本来都要检查一遍,跳过后检查量大幅下降(实验 4),代价是声明文件之间的冲突和错误不会报出来。
解决的问题
同一套 TypeScript 代码要在不同环境运行:浏览器原生 ESM、打包工具、Node.js、测试运行器。tsconfig.json 把「运行环境提供什么 API」「模块怎么解析」「检查到什么程度」「输出放在哪里」写成显式配置,让编译期的假设和运行时的行为一致。
严格选项解决的是检查的覆盖面:关闭 strict 时,实验 1 中的六类错误一个都不报,包括隐式 any、可能为 undefined 的值、参数类型不安全的回调、未初始化的类字段。
6.0 改默认值,是因为旧默认值对新项目几乎都是错的:target: es5 早已不是需要支持的运行时,strict: false 让新项目一开始就少了一半检查,自动加载全部 @types 会把不相关的全局声明混进来,并拖慢编译。
适用场景
浏览器原生 ESM、不用打包工具:下面这份配置在 7.0.2 下可以直接使用(实验 3)。它没有写 types,6.0 起默认就是 [],不会加载任何 @types 全局声明:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
"compilerOptions": {
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "Bundler",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"rootDir": "src",
"outDir": "js",
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"verbatimModuleSyntax": true,
"noEmitOnError": true,
"sourceMap": true
},
"include": ["src/**/*.ts"]
}
这里的 Bundler 只是让编译期解析能工作,浏览器不会补扩展名,所以源码中的相对导入必须写完整的 .js。想让编译器替你检查这一点,可以改用 "module": "nodenext",省略扩展名会报 TS2835。isolatedModules 已被 verbatimModuleSyntax 隐含,不必再写。
Vite 等打包工具:用 "module": "esnext"、"moduleResolution": "bundler",开启 verbatimModuleSyntax(单文件转译器需要,见《TypeScript 类型擦除:类型在运行时不存在,外部数据怎样校验》),"noEmit": true,类型检查由 tsc --noEmit 单独完成。
Node.js:用 "module": "nodenext","types": ["node"]。用 Node.js 直接运行 .ts 时,Node.js 不读取 tsconfig.json,配置只对 tsc 检查生效。
严格选项的取舍:
strict保持默认开启。noUncheckedIndexedAccess适合大量处理数组、字典、表格记录的代码,它让arr[i]的类型带上undefined,这确实是运行时可能出现的值;确定的元组位置不受影响。exactOptionalPropertyTypes适合 PATCH 类接口,「不传这个字段」和「传undefined」含义不同时开启。- 存量项目迁移时,可以先显式写
"strict": false,再逐个打开子开关。
无类型的第三方库:先找库自带的声明,再找版本匹配的 @types;都没有时只为实际用到的 API 写最小声明,并在集成层用测试覆盖。不要用简写的 declare module "x"; 一次性放过。
Source map:开启 sourceMap 后生成 .js.map,sources 字段指回 .ts 源文件(实验 4),浏览器开发者工具据此在源码上断点。生产环境是否部署 .map 文件取决于是否允许公开源码。
报错定位:
| 报错 | 常见原因 | 处理方向 |
|---|---|---|
TS18047 / TS18048 ... is possibly 'null'/'undefined' | DOM 查询、find、可选属性、开启 noUncheckedIndexedAccess 后的索引读取 | 显式判断,或抛出带上下文的错误 |
TS18046 ... is of type 'unknown' | catch 变量、未校验的外部数据 | 收窄或运行时校验后再访问 |
TS2322 / TS2345 ... is not assignable to ... | 宽泛的字符串被当作字面量联合使用,或者对象结构不符 | 用守卫校验取值,不要直接断言 |
TS2769 No overload matches this call | 实参不匹配任何一个公开重载 | 对照最后一个重载的报错细节检查入参 |
TS7016 Could not find a declaration file | 库没有声明 | 安装 @types 或写最小声明 |
TS2591 Cannot find name 'process' | 6.0 起 types 默认为空 | 在 types 中显式列出 node |
TS2835 Relative import paths need explicit file extensions | nodenext 下省略扩展名 | 写 .js |
类型检查只证明各部分的类型契约一致,分页计算、过滤条件、异常输入的处理仍需要测试。纯函数可以用 Node.js 自带的 node:test 运行,组件测试留到后续的工程化专题。
失效条件
- 旧项目直接升级到 6.0/7.0。
- 触发条件:配置里没写
strict,依赖自动加载的@types。 - 后果:
strict变为开启,原来不报的错误全部出现;process、describe等全局名报 TS2591。 - 如何观测:实验 1、实验 3。升级前先在旧版本上显式写出
"strict": false和"types": [...],再升级,报错数量不会突变。
- 触发条件:配置里没写
- 配置里有已删除的选项。
- 触发条件:
target: es5、moduleResolution: node、baseUrl等。 - 后果:6.0 报 TS5107/TS5101,加
ignoreDeprecations可继续;7.0 报 TS5108/TS5102,无法屏蔽。 - 如何观测:实验 2。
baseUrl按报错提示改为paths,node10改为bundler或nodenext。
- 触发条件:
- 没写
rootDir,源码在子目录里。- 触发条件:源码在
src/下,tsconfig 只写了outDir。 - 后果:7.0.2 报 TS5011,仍然生成文件,但输出路径变成
outDir/src/...,HTML 或部署脚本里引用的outDir/main.js不存在。 - 如何观测:实验 4,显式写
"rootDir": "src"。
- 触发条件:源码在
moduleResolution与运行环境不一致。- 触发条件:配置为
bundler,但产物直接由浏览器或 Node.js 加载;或者源码中省略了扩展名。 - 后果:
tsc检查通过,运行时找不到模块。 - 如何观测:实验 3 中
tsc退出码为 0,node运行报ERR_MODULE_NOT_FOUND。浏览器原生 ESM 同样不补扩展名,会请求不带.js的 URL,在开发者工具的网络面板中可以看到失败的请求。
- 触发条件:配置为
- 手写声明与库的实现不一致。
- 触发条件:
declare module中声明了库没有的函数,或参数、返回类型写错。 - 后果:编译通过,调用时抛
TypeError。 - 如何观测:实验 3 中
destroyWidget只存在于声明里,运行时is not a function。声明文件改动应伴随调用该 API 的测试。
- 触发条件:
- 简写模块声明。
- 触发条件:
declare module "legacy-widget"; - 后果:模块的所有导出都是
any,createWidget(123).anything.goes()也能通过。 - 如何观测:实验 3 中这一行编译通过。在编辑器中悬停导入名,类型显示为
any;typescript-eslint 的no-unsafe-*系列规则可以报出any的使用位置。
- 触发条件:
- 以为
strict包含所有严格检查。- 触发条件:只开
strict,用names[1]读取数组,用{ mobile: undefined }表示「不修改」。 - 后果:
names[1]的类型是string,运行时是undefined;PATCH 请求把字段清空。 - 如何观测:实验 1 的第二组命令,加上两个选项后才报 TS2322 和 TS2375。
- 触发条件:只开
- 用
skipLibCheck掩盖声明冲突。- 触发条件:依赖树里有同一个库的两份类型,或升级后
.d.ts报错,直接开启skipLibCheck。 - 后果:冲突的声明不再报错,源码按其中一份声明检查,可能与实际加载的版本不符。官方文档建议用包管理器的
resolutions等机制保证依赖只有一份,而不是跳过检查。 - 如何观测:关闭
skipLibCheck跑一次tsc --noEmit,查看node_modules下的报错。
- 触发条件:依赖树里有同一个库的两份类型,或升级后
实验验证
环境:Docker 官方镜像 node:22(Node v22.23.5),typescript@7.0.2,typescript@6.0.3(npm 别名 ts6),@types/node@22.20.7。
实验 1:默认配置下的严格检查
sample.ts 每一段对应一个检查项:第 2 行 noImplicitAny,第 6 行 strictNullChecks,第 10 行 strictFunctionTypes,第 12 行 strictPropertyInitialization,第 15 行 strictBindCallApply,第 17 行 useUnknownInCatchVariables,第 20 行 noUncheckedIndexedAccess,第 23 行 exactOptionalPropertyTypes。tsconfig 里没有写 strict:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
===== Version 7.0.2
$ cat defaults/tsconfig.json
{ "compilerOptions": { "noEmit": true, "lib": ["es2022", "dom"] }, "files": ["sample.ts"] }
$ tsc -p defaults --pretty false
defaults/sample.ts(2,22): error TS7006: Parameter 'x' implicitly has an 'any' type.
defaults/sample.ts(6,10): error TS18048: 'el' is possibly 'undefined'.
defaults/sample.ts(10,22): error TS2322: Type '(v: string) => void' is not assignable to type '(v: string | number) => void'.
Types of parameters 'v' and 'v' are incompatible.
Type 'string | number' is not assignable to type 'string'.
Type 'number' is not assignable to type 'string'.
defaults/sample.ts(12,14): error TS2564: Property 'name' has no initializer and is not definitely assigned in the constructor.
defaults/sample.ts(15,12): error TS2345: Argument of type 'undefined' is not assignable to parameter of type 'Window'.
defaults/sample.ts(17,50): error TS18046: 'e' is of type 'unknown'.
$ tsc -p strictoff --pretty false # 同上,另加 "strict": false
$ tsc -p defaults --pretty false --noUncheckedIndexedAccess --exactOptionalPropertyTypes
...
defaults/sample.ts(20,7): error TS2322: Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
defaults/sample.ts(23,7): error TS2375: Type '{ mobile: undefined; }' is not assignable to type 'Patch' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.
...
strict: false 时没有任何输出。6.0.3 的结果逐行相同。
实验 2:旧配置在 6.0 和 7.0 下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ cat legacy/tsconfig.json && tsc -p legacy --pretty false
{ "compilerOptions": { "noEmit": true, "target": "es5", "moduleResolution": "node", "baseUrl": "." }, "files": ["a.ts"] }
legacy/tsconfig.json(1,50): error TS5108: Option 'target=ES5' has been removed. Please remove it from your configuration.
legacy/tsconfig.json(1,77): error TS5108: Option 'moduleResolution=node10' has been removed. Please remove it from your configuration.
legacy/tsconfig.json(1,85): error TS5102: Option 'baseUrl' has been removed. Please remove it from your configuration.
Use '"paths": {"*": ["./*"]}' instead.
...
===== Version 6.0.3
...
legacy/tsconfig.json(1,50): error TS5107: Option 'target=ES5' is deprecated and will stop functioning in TypeScript 7.0. Specify compilerOption '"ignoreDeprecations": "6.0"' to silence this error.
legacy/tsconfig.json(1,77): error TS5107: Option 'moduleResolution=node10' is deprecated and will stop functioning in TypeScript 7.0. Specify compilerOption '"ignoreDeprecations": "6.0"' to silence this error.
Visit https://aka.ms/ts6 for migration information.
legacy/tsconfig.json(1,85): error TS5101: Option 'baseUrl' is deprecated and will stop functioning in TypeScript 7.0. Specify compilerOption '"ignoreDeprecations": "6.0"' to silence this error.
...
实验 3:模块解析、导入方式与声明文件
1
2
3
4
5
$ tsc -p vms --pretty false # verbatimModuleSyntax
vms/main.ts(1,10): error TS1484: 'Employee' is a type and must be imported using a type-only import when 'verbatimModuleSyntax' is enabled.
$ tsc -p nodenext --pretty false # module: nodenext,相对导入省略扩展名
nodenext/main.ts(1,32): error TS2835: Relative import paths need explicit file extensions in ECMAScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Did you mean './model.js'?
把「适用场景」中浏览器原生 ESM 的配置原样使用,main.ts 中一条导入写了 ./model.js,另一条写成 ./label:
1
2
3
4
5
$ tsc -p browseresm --pretty false # 浏览器原生 ESM 配置(另加 "types": []),label 的导入省略了 .js
tsc exit=0
...
$ node browseresm/js/main.js # 按浏览器/Node 原生 ESM 规则解析
Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/work/ts/e5_tsconfig/browseresm/js/label' imported from /work/ts/e5_tsconfig/browseresm/js/main.js
types 的新默认值,以及一个只有 JS、没有声明的包 legacy-widget(只导出 createWidget):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$ tsc -p typesdefault --pretty false # TS 6/7 默认 types: []
typesdefault/main.ts(1,13): error TS2591: Cannot find name 'process'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig.
$ tsc -p typesdefault/tsconfig.node.json --pretty false # 显式 "types": ["node"]
tsc exit=0
$ tsc -p untyped --pretty false # 第三方库只有 JS,没有声明
untyped/src/main.ts(1,45): error TS7016: Could not find a declaration file for module 'legacy-widget'. '/work/ts/e5_tsconfig/untyped/node_modules/legacy-widget/index.js' implicitly has an 'any' type.
...
$ tsc -p untyped/tsconfig.decl.json --pretty false # 加上手写的 declare module
tsc exit=0
$ node 运行同一段逻辑(编译为 CommonJS 后)
{ mounted: 'root' }
TypeError: (0 , legacy_widget_1.destroyWidget) is not a function
$ tsc -p untyped/tsconfig.shorthand.json --pretty false # declare module "legacy-widget";
tsc exit=0
实验 4:输出布局、source map 与 skipLibCheck
1
2
3
4
5
6
7
8
9
$ tsc -p srcmap && cat srcmap/js/main.js.map
main.js
main.js.map
{"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AACA,MAAM,IAAI,GAAe,CAAC,EAAE,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;AACvD,MAAM,UAAU,KAAK,CAAC,CAAW;IAC/B,OAAO,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;AACnC,CAAC;AACD,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC"}
...
$ tsc -p srcmap/tsconfig.norootdir.json && find srcmap/js2 -type f # 不写 rootDir
srcmap/tsconfig.norootdir.json(1,24): error TS5011: The common source directory of 'tsconfig.norootdir.json' is './src'. The 'rootDir' setting must be explicitly set to this or another path to adjust your output's file layout.
Visit https://aka.ms/ts6 for migration information.
srcmap/js2/src/main.js
只含一个空文件、lib 为 es2022,dom 时的检查量:
1
2
3
4
5
===== skipLibCheck 对检查量的影响(空文件 + lib es2022,dom)
Version 7.0.2 默认 Types: 31816 Instantiations: 28112 Check time: 0.097s
Version 7.0.2 --skipLibCheck Types: 340 Instantiations: 0 Check time: 0.000s
Version 6.0.3 默认 Types: 27905 Instantiations: 27046 Check time: 0.37s
Version 6.0.3 --skipLibCheck Types: 85 Instantiations: 0 Check time: 0.00s
空文件下的差值全部来自检查标准库声明本身。真实项目中源码引用的声明仍然要检查,节省的比例会小于这里。
脚本和原始输出:source/experiments/frontend/fe-b/ts/e5_tsconfig/(run.sh 与 out.txt 对应实验 1、2 和实验 3 前半、实验 4 的 skipLibCheck;run_extra.sh 与 out_extra.txt 对应其余部分)。untyped/fixture/ 是伪造的无类型包,run_extra.sh 运行前把它复制进 node_modules。
