如何在Typescript中将类型本地添加到未类型化的npm模块?

时间:2020-09-30 15:44:04

标签: typescript npm

我知道至少从2017年以来,就一直有人在其他地方回答这个问题,但是我无法完成这项工作。我的项目noImplicitAny: true中有tsconfig.json。我正在尝试使用clamscan既不是本机类型也不可用的@types。我的问题不是特定于此软件包的。

因此,当我在import NodeClam from 'clamscan'code.ts时出现以下错误:

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软件包做出贡献,但是问题在于,仅针对我的项目在本地注释/增强该软件包。

1 个答案:

答案 0 :(得分:0)

试试这个:

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