如何让tsc仅对指定.ts文件做类型检查但不生成JavaScript?
解决TypeScript类型测试文件不生成JS但保留类型检查的问题
方案1:使用TypeScript 5.0+的overrides配置(推荐)
如果你的TypeScript版本是5.0及以上,可直接在tsconfig.json里通过overrides字段为类型测试文件单独设置规则,无需拆分配置:
{ "compilerOptions": { "rootDir": "./src", "outDir": "./dist", "strict": true, "target": "ES2020" // 其他业务代码编译配置 }, "include": [ "./src/**/*", "./type-tests/**/*" // 包含类型测试文件,确保被类型检查 ], "overrides": [ { "files": ["./type-tests/**/*.ts"], "compilerOptions": { "noEmit": true, // 不对这些文件生成任何输出 "rootDir": undefined // 取消rootDir限制,允许文件不在rootDir下 } } ] }
运行tsc时,业务代码会正常编译到outDir,type-tests下的文件仅做类型检查,不会生成JS,且不受rootDir约束。
方案2:拆分tsconfig配置(兼容低版本TypeScript)
若TypeScript版本低于5.0,可拆分两个配置文件:
- 主配置文件
tsconfig.json:负责业务代码编译
{ "compilerOptions": { "rootDir": "./src", "outDir": "./dist", "strict": true, "target": "ES2020" }, "include": ["./src/**/*"] }
- 类型测试配置文件
tsconfig.type-tests.json:负责类型测试文件的检查,不生成输出
{ "extends": "./tsconfig.json", // 继承主配置的类型检查规则 "compilerOptions": { "noEmit": true, // 禁用输出 "rootDir": undefined // 解除rootDir限制 }, "include": ["./type-tests/**/*"] }
在package.json的scripts中添加命令:
{ "scripts": { "build": "tsc", "check-types": "tsc -p tsconfig.type-tests.json" } }
运行npm run build编译业务代码,npm run check-types单独检查类型测试文件的类型正确性。
注意事项
- 类型测试文件建议放在专属目录(如
type-tests)或用统一命名后缀(如*.type-test.ts),方便规则匹配。 - 使用
overrides时,确保files路径匹配准确,避免误影响业务文件。
内容的提问来源于stack exchange,提问作者joegomain
相关产品推荐
相关产品推荐

