typescript 我应该在哪里放置自定义 .d.ts 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45382951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:46:34  来源:igfitidea点击:

Where should I place custom .d.ts files?

typescripttypescript-typings

提问by Rogach

I'm trying to provide typings for the package that does not have them:

我正在尝试为没有它们的包提供类型:

error TS7016: Could not find a declaration file for module 'inputmask-core'. './node_modules/inputmask-core/lib/index.js' implicitly has an 'any' type.
Try `npm install @types/inputmask-core` if it exists or add a new declaration (.d.ts) file containing `declare module 'inputmask-core';`

I'm using ts-loader in webpack with typescript 2.4.2, and I have the following type roots set up in tsconfig.json:

我在带有打字稿 2.4.2 的 webpack 中使用 ts-loader,并且我在 tsconfig.json 中设置了以下类型根:

"typeRoots": [
  "./node_modules/@types",
  "./src/client/types"
]

I tried to mimic the package structure in node_modules/@types:

我试图模仿包结构node_modules/@types

src/client/types
|--inputmask-core
  |--index.d.ts

With the following in index.d.ts:

在以下内容中index.d.ts

declare class InputMask {}
export default InputMask;

But the error is still there. What am I doing wrong? Where should I place those custom .d.ts files?

但是错误仍然存​​在。我究竟做错了什么?我应该在哪里放置这些自定义 .d.ts 文件?

And what is the difference between node_modules/@typesand any other type root? Why does TypeScript treat them differently?

node_modules/@types和任何其他类型的根有什么区别?为什么 TypeScript 对它们的处理方式不同?

回答by Ville

Use paths instead of typeRoots --

使用路径而不是 typeRoots --

via https://github.com/Microsoft/TypeScript/issues/22217#issuecomment-369783776

通过https://github.com/Microsoft/TypeScript/issues/22217#issuecomment-369783776

"typeRoots" is meant for global code. i.e. something that is declared in the global namespace, and you want to include it. For modules, they have their own scope, all you need is path mapping.. something like:

“typeRoots”用于全局代码。即在全局命名空间中声明的东西,并且您想包含它。对于模块,它们有自己的范围,您只需要路径映射.. 类似于:

{
"compilerOptions": {
    "target": "es2017",
    "baseUrl": "./",
    "paths": {
        "*" : ["src/client/@custom_types/*"]
    }
},
"exclude": ["node_modules", "src/client/@custom_types", ...]
}

Note: baseUrl is required with paths, and you probably also want to add the dir to exclude.

注意:路径需要 baseUrl,您可能还想添加要排除的目录。

回答by Rogach

Possible solution: place the following in index.d.ts, and it will compile:

可能的解决方案:将以下内容放在 index.d.ts 中,它将编译:

declare module "inputmask-core" {
    declare class InputMask {}
    export default InputMask;
}

I still don't understand the special handling that node_modules/@typesgets, though.

不过,我仍然不明白得到的特殊处理node_modules/@types