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

Rog*_*ach 26 typescript typescript-typings

我正在尝试为没有它们的包提供打字:

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';`
Run Code Online (Sandbox Code Playgroud)

我在webpack中使用ts-loader和typescript 2.4.2,我在tsconfig.json中设置了以下类型的根:

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

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

src/client/types
|--inputmask-core
  |--index.d.ts
Run Code Online (Sandbox Code Playgroud)

具体如下index.d.ts:

declare class InputMask {}
export default InputMask;
Run Code Online (Sandbox Code Playgroud)

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

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

Rog*_*ach 12

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

declare module "inputmask-core" {
    declare class InputMask {}
    export default InputMask;
}
Run Code Online (Sandbox Code Playgroud)

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


Vil*_*lle 6

使用路径而不是typeRoots-

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

“ typeRoots”用于全局代码。即在全局名称空间中声明的内容,并且您要包含它。对于模块,它们有自己的作用域,您只需要路径映射即可。

{
"compilerOptions": {
    "target": "es2017",
    "baseUrl": "./",
    "paths": {
        "*" : ["src/client/@custom_types/*"]
    }
},
"exclude": ["node_modules", "src/client/@custom_types", ...]
}
Run Code Online (Sandbox Code Playgroud)

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

  • 这太奇怪了。我尝试过这个,但它不会让步。我仍然收到“TS2307:找不到模块”错误。我的编译器选项中有这个: `"baseUrl": ".", "paths": { "~/*": ["src/*"], "*": ["@custom_types/*"] }`但是像“从'./svg/inline/icons.svg'导入图标”这样的路径不起作用。有任何想法吗? (2认同)