如何在 TypeScript 中本地为未标记类型的 npm 模块添加类型?

4
我知道自2017年以来已经有人提出并回答了类似的问题,但我无法让其正常工作。我在我的项目的`tsconfig.json`中设置了`noImplicitAny:true`。我正在尝试使用既不是原生类型也不在`@types`中可用的`clamscan`。我的问题不限于此程序包。
当我在`code.ts`中导入`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 模块进行类型标注呢?

我知道我可以为 DefinitelyTyped 或者 clamscan 包做出贡献,但这个问题是关于仅为我的项目本地注释/增强包的。


1
我怀疑 TypeScript 找不到你的声明文件。尝试将其放在路径 src/@types/clamscan/index.d.tssrc/@types/clamscan.d.ts 中。或者编辑你的 .tsconfig 中的 typeRoots 属性,将其包含在你存储它的路径中。如果我在导入模块之后声明类型,则会出现“无效模块…”错误。 - Linda Paiste
谢谢你的建议。我无法在src/中使它工作,但是现在我把它放在node_modules/@types/clamscan/index.d.ts中了。接下来我会尝试使用typeRoots来看看是否能有更好的解决办法。 - Antoine
有人解决了这个问题吗? - Douglas Gaskell
@DouglasGaskell 不是很理想,我在node_modules/@types中工作,所以最终我的类型定义被合并到上游包中,这样对其他人也有用 - 所以问题解决了,但我没有针对原始问题的技术解决方案。 - Antoine
2个回答

2

试试这个:

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
    }

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

0

为了让它与digest-stream一起正常工作,必须这样做:

declare module "digest-stream" {
  export default function digestStream(algorithm: string, inputEncoding: string, digestEncoding?: any, options?: any, listenerFn?: any): any
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接