网站搜索

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


我正在尝试为没有类型定义的包提供类型信息:

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';`

我在 webpack 中使用 ts-loader 和 TypeScript 2.4.2,并且我在 tsconfig.json 中设置了以下类型根目录:

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

我尝试在 node_modules/@types 中模仿包结构:

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

在 index.d.ts 中使用以下内容:

declare class InputMask {}
export default InputMask;

但错误仍然存在。我做错了什么?我应该把那些自定义的 .d.ts 文件放在哪里?

那么 node_modules/@types 与其他类型根目录有什么区别?为什么 TypeScript 对它们的处理方式不同?

答案#1

使用 paths 而不是 typeRoots

  • https://github.com/Microsoft/TypeScript/issues/22217#issuecomment-369783776
  • https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping

“typeRoots” 是用于全局代码的。也就是说,它是声明在全局命名空间中的内容,你想要包含它。对于模块,它们有自己的作用域,你只需要路径映射……类似这样:

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

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

答案#2

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

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

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

相关文章