TypeScript 没有在 tsconfig 中获取我的自定义类型定义

ano*_*ser 5 javascript node.js typescript

我正在使用 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/**/*"]
}
Run Code Online (Sandbox Code Playgroud)

自定义类型/自定义.d.ts

declare global {
  const foo: string;

  namespace NodeJS {
    interface Global {
      foo: string;
    }
  }
}
export default global;

Run Code Online (Sandbox Code Playgroud)

src/app.js

let bar = foo; // Cannot find name 'foo'.ts(2304)
Run Code Online (Sandbox Code Playgroud)

但是,当我在 tsconfig 中执行此操作时:

{
  ...
  },
  "include": ["src/**/*", "custom_types/custom.d.ts"]
}
Run Code Online (Sandbox Code Playgroud)

一切都很完美。所以这让我认为我tsconfig是错误的并且TypesScript完全忽略了这一部分:

"typeRoots": ["./custom_types/", "node_modules/@types/"],
Run Code Online (Sandbox Code Playgroud)

当尝试使用我自己的自定义类型定义指定文件夹路径时,我做错了什么?

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/"],

Run Code Online (Sandbox Code Playgroud)

use*_*er1 7

我不久前做过这件事,我记得那是一场斗争。他们可能在新版本的打字稿中改变了它,但我还没有测试过。我不久前的 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"
  ]
Run Code Online (Sandbox Code Playgroud)

查看包含路径设置,我在其中指定了自定义类型定义文件夹的位置。这适用于打字稿 2.9.1。

关于typeRoots:添加此选项是为了对类型进行向后兼容性支持,这就是为什么它甚至不在文档中,并且如果您不使用类型,则不应使用它。更多信息可以在这里找到。