Antoine
Antoine

Reputation: 14094

How to locally add types to untyped npm modules in typescript?

I know this has been asked an answered elsewhere since at least 2017, but I can't make this work. I have noImplicitAny: true in my tsconfig.json in my project. I'm trying to use clamscan which is neither natively typed nor available in @types. My question is not specific to this package.

So when I import NodeClam from 'clamscan' in code.ts I get the following error:

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)

So I created a clamscan.d.ts file with:

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

I also tried simply declare module 'clamscan';. In both cases I get:

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

On the other hand, declare module '*'; is accepted by the compiler but isn't quite what I want (and doesn't solve the original error anyways). So, how can I type an untyped foreign npm module ?

I understand that I can contribute to DefinitlyTyped or the clamscan package, but the question is about annotating/augmenting the package locally just for my project.

Upvotes: 5

Views: 4520

Answers (2)

Edwin Joassart
Edwin Joassart

Reputation: 958

Had to do this for it to work with digest-stream :

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

Upvotes: 0

Edward Casanova
Edward Casanova

Reputation: 1064

Try this:

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

or create a single file with only this inside "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
    }

If this doesn't work take a look at this solution

Upvotes: 2

Related Questions