Warm tip: This article is reproduced from serverfault.com, please click

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

(javascript - TypeScript is not picking up my custom type defenitions in tsconfig)

发布于 2020-11-28 07:46:01

我正在使用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:有 许多答案建议使用baseUrlpaths但是,这样做对我没有任何帮助:

 "baseUrl": "./",
    "paths": {
      "@custom_types": ["*", "./custom_types/*"]
    },
    "typeRoots": ["@custom_types/custom.d.ts", "node_modules/@types/"],

Questioner
anotheruser
Viewed
0
user1 2020-11-30 16:15:20

我前一阵子做了,我记得那是一场挣扎。他们可能会在较新版本的打字稿中进行更改,但我尚未对其进行测试。我前一阵子的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"
  ]

看一下includepath设置,在其中指定自定义类型定义文件夹的位置。这适用于打字稿2.9.1。

关于typeRoots:添加为向后兼容性支持这一选项分型,这就是为什么它甚至不是在文档中,它不应该被使用,如果你不使用分型更多信息可以在这里找到