TypeScript tsconfig.json中strict模式启用后类型检查失效问题
TypeScript strict模式在tsconfig.json中未生效的问题
问题现象
使用CLI参数--strict执行编译时,能正常检测到类型错误:
$ ./node_modules/.bin/tsc --strict main.ts main.ts:6:5 - error TS2322: Type 'null' is not assignable to type 'Person'. 6 return null; ~~~~~~~~~~~~
但将strict配置写入tsconfig.json后,执行./node_modules/.bin/tsc main.ts却未检测到任何类型错误:
$ cat tsconfig.json { "compilerOptions": { "strict": true } } $ ./node_modules/.bin/tsc main.ts $ # no typing errors found 😖😖😖
相关源码:
class Person { constructor(private lastName: string){} public getFriend(name: string): Person { if (name == "Someone") { return new Person("Mr."); } return null; } }
原因分析
这是TypeScript的设计规则:当你在tsc命令后显式指定单个/多个输入文件时,TypeScript会忽略tsconfig.json配置文件,转而使用默认编译配置,再叠加CLI传入的参数。此时tsconfig.json里的strict: true未被加载,自然不会生效。
解决方法
有两种方式可以让tsconfig.json的配置生效:
- 方式1:直接执行
tsc不带文件名,让TypeScript自动读取当前目录下的tsconfig.json:./node_modules/.bin/tsc - 方式2:如果需要指定编译文件同时加载
tsconfig,使用--project(简写-p)参数指定配置文件:./node_modules/.bin/tsc -p tsconfig.json main.ts
内容的提问来源于stack exchange,提问作者OrenIshShalom
相关产品推荐
相关产品推荐

