首页 > 解决方案 > 如何在打字稿中将类型本地添加到无类型的 npm 模块?

问题描述

我知道至少自 2017 年以来,这已在其他地方得到回答,但我无法完成这项工作。我noImplicitAny: truetsconfig.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但问题是仅针对我的项目在本地注释/扩充该软件包。

标签: typescriptnpm

解决方案


尝试这个:

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
    }

如果这不起作用,请查看此解决方案


推荐阅读