在 Typescript 游乐场中的这个示例中,我尝试在命名空间内使用不存在的类型,但出现错误:
这是预料之中的。
但是在我本地的开发环境中,Typescript 基本上接受任何不存在的类型作为
any
。
注意:这只发生在
d.ts
文件内。
不知道这是否重要,但我正在使用
noImplicitAny: true
标志。
查看我的
tsconfig.json
文件:
{
"compilerOptions": {
"allowJs": true,
"baseUrl": ".",
"esModuleInterop": true,
"jsx": "react",
"module": "CommonJS",
"moduleResolution": "Node",
"noEmit": true,
"noImplicitAny": true,
"noImplicitReturns": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strictNullChecks": true,
"target": "ES6",
"paths": {
"@src/*": ["./src/*"],
}
},
"include": [
"src/**/*",
"functions/src/**/*",
"functions/index.ts"
],
}
如何让 Typescript 检测到这些错误?
声明文件,带有
.d.ts
扩展名的文件,由 --skipLibCheck
编译器选项覆盖。
通过指定
{
"compilerOptions": {
"skipLibCheck": true
}
}
在您的
tsconfig.json
中,您已告诉 TypeScript 不要验证此文件。
一般来说,您有两种选择来强制验证此文件。
将文件从
.d.ts
重命名为 .ts
。这是最直接的方法,也是侵入性最小的方法。 .ts
仅包含声明的文件完全有效。
删除上面的
"skipLibCheck": true
配置,从而在 .d.ts
文件中强制执行类型检查,这是默认行为。