我正在使用tsconfig来检查我的js文件。我在我的自定义类型定义中custom_types\custom.d.ts
tsconfig.json
{
"compilerOptions": {
"target": "es2020",
"module": "commonjs",
"allowJs": true,
"checkJs": true,
"outDir": "./dist",
"strict": true,
"typeRoots": ["./custom_types/", "node_modules/@types/"],
"types": ["node"],
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"]
}
custom_types / custom.d.ts
declare global {
const foo: string;
namespace NodeJS {
interface Global {
foo: string;
}
}
}
export default global;
src / app.js
let bar = foo; // Cannot find name 'foo'.ts(2304)
但是,当我在tsconfig中执行此操作时:
{
...
},
"include": ["src/**/*", "custom_types/custom.d.ts"]
}
一切正常。因此,这使我认为自己tsconfig
是错的,并TypesScript
完全忽略了这一部分:
"typeRoots": ["./custom_types/", "node_modules/@types/"],
尝试使用自己的自定义类型定义指定文件夹的路径时,我在做什么错?
ps正确地"node_modules/@types/"
被拾取了TypeScript
(里面的所有东西@types
对我来说都是可用的)。但是"./custom_types/"
被忽略了。
UPD:有
许多答案建议使用baseUrl
和paths
。但是,这样做对我没有任何帮助:
"baseUrl": "./",
"paths": {
"@custom_types": ["*", "./custom_types/*"]
},
"typeRoots": ["@custom_types/custom.d.ts", "node_modules/@types/"],
我前一阵子做了,我记得那是一场挣扎。他们可能会在较新版本的打字稿中进行更改,但我尚未对其进行测试。我前一阵子的tsconfig看起来像:
"compilerOptions": {
"module": "commonjs",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"skipLibCheck": true,
"sourceMap": true,
"outDir": "./dist",
"lib": [
"es2017"
],
"baseUrl": ".",
"paths": {
"*": [
"*",
"./types/*"
]
}
},
"include": [
"types/**/*.d.ts",
"src/**/*"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
看一下include和path设置,在其中指定自定义类型定义文件夹的位置。这适用于打字稿2.9.1。
关于typeRoots:添加为向后兼容性支持这一选项分型,这就是为什么它甚至不是在文档中,它不应该被使用,如果你不使用分型。更多信息可以在这里找到。
感谢您的回答!您的建议确实有效,但仅要感谢
"include": ["types/**/*.d.ts]"
。我通过放置可以达到相同的效果"include": ["src/**/*", "custom_types/custom.d.ts"]
。我要在这里弄清楚的是为什么TypeScript忽略了我的typeRoots
@anotheruser在您的情况下,您具有用于全局的类型定义,而在我的情况下,我具有我用JS编写的库的类型定义,因此路径是必需的,但是对于您的情况,仅包含应该起作用。如果答案有帮助,您可以选择它作为正确的答案。谢谢。
@anotheruser BTW typeRoots是用于向后兼容支持加分型,这就是为什么它甚至不是在文档中,所以你不应该使用它。
请稍等...所以这就是为什么我无法找到有关此bs的任何明确信息吗?您是否有任何github讨论或其他SO主题可供参考?因为这听起来像是我正在尝试实现某些我什至不应该尝试实现的目标...
@anotheruser,这里你去