【问题标题】:How to locally add types to untyped npm modules in typescript?如何在打字稿中将类型本地添加到无类型的 npm 模块?
【发布时间】:2021-01-16 08:04:53
【问题描述】:

我知道至少从 2017 年开始,其他地方就有人问过这个问题,但我无法完成这项工作。我的项目中有noImplicitAny: true 在我的tsconfig.json 中。我正在尝试使用clamscan,它既不是本机类型,也不是@types 中可用的。我的问题不是针对这个包的。

所以当我在code.tsimport NodeClam from 'clamscan' 时出现以下错误:

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

所以我创建了一个clamscan.d.ts 文件:

declare module 'clamscan' {
  // the declarations I use
}

我也简单地尝试了declare module 'clamscan';。在这两种情况下,我都得到:

Invalid module name in augmentation. Module 'clamscan' resolves to an untyped module at '.../node_modules/clamscan/index.js', which cannot be augmented.ts(2665)

另一方面,declare module '*'; 被编译器接受,但不是我想要的(并且无论如何也不能解决原始错误)。那么,我怎样才能输入一个无类型的外部 npm 模块呢?

我知道我可以为 DefinitlyTypedclamscan 包做出贡献,但问题是只为我的项目在本地注释/扩充包。

【问题讨论】:

  • 我怀疑 typescript 找不到您的声明文件。尝试输入路径src/@types/clamscan/index.d.tssrc/@types/clamscan.d.ts。或编辑.tsconfig 中的typeRoots 属性以包含存储它的路径。如果我在导入模块后声明了类型,则会收到“无效模块...”错误。
  • 感谢您的提示。不能让它在 src/ 中的任何地方工作,但我现在把它放在 node_modules/@types/clamscan/index.d.ts 中。我会和 typeRoots 一起玩,看看我能不能做得更好。
  • 每一个都解决这个问题?
  • @DouglasGaskell 不是真的,我在 node_modules/@types 工作,这显然不是理想的,所以我最终将我的类型定义合并到上游包中,以便对其他人有用 -所以我想问题已经解决了,但我没有针对我原来的问题的技术解决方案

标签: typescript npm


【解决方案1】:

试试这个:

declare module 'clamscan' {
   import * as Clamscan from 'clamscan';
  export default Clamscan
}

或者在“clamscan.d.ts”中创建一个只有这个的文件

declare module 'clamscan' {
       import * as Clamscan from 'clamscan'; // or import Clamscan from "clamscan" or import {Clamscan} from "clamscan" . It depends of how the import is handled
    }

如果这不起作用,请查看solution

【讨论】:

    猜你喜欢
    • 2018-04-27
    • 1970-01-01
    • 2018-04-23
    • 2017-11-13
    • 1970-01-01
    • 2021-08-06
    • 2022-12-03
    • 2017-02-26
    • 2021-10-21
    相关资源
    最近更新 更多