Home > database >  How to use TypeScript w/ a library with no definition file?
How to use TypeScript w/ a library with no definition file?

Time:05-18

So I’m trying to use the pino-clf library in my koa TS project.

I keep getting this when I try to compile:

TSError: ⨯ Unable to compile TypeScript:
src/modules/logger/index.ts:5:21 - error TS7016: Could not find a declaration file for module 'pino-clf'. '/dev/webservices/node_modules/pino-clf/index.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/pino-clf` if it exists or add a new declaration (.d.ts) file containing `declare module 'pino-clf';`

5 import pinoClf from 'pino-clf'
                      ~~~~~~~~~~

pino-clf doesn’t have a def file and there’s no @types/pino-clf available.

I tried adding a pino-clf.d.ts file in the folder of the file that I’m importing the lib into w/ declare module 'pino-clf' in it. While that got the red squigglies in my IDE to go away, TS still refuses to compile.

How in the world do we use use a lib that’s just plain JS w/ TS and w/o adding a ts-ignore?

CodePudding user response:

So there are two ways this can be accomplished.

Solution One: Probably the easiest

You can just use require ex: const pinoClf = require("pinoClf") - the down-side is that dot reference or intellisense isn't available but if you know the methods you want to use its no biggie.

Solution Two:

Create you own typeDef file in the root of you project. For example,

pino-clf.custom.d.ts

declare module "pino-clf.custom" {
   const pinoClfJs = require("pinoClf");
    export default class pinoClf {
      commonLog (type: string, dest: NodeJS.WriteStream, ancillary: any): void {
         pinoClfJs.commonLog(type, dest, ancillary);
       }
    }
}

then in you tsconfig.json file include the new typeDef file:

{
  ... // assuming src is already there
"include": [
    "src", "pino-clf.custom.d.ts"
  ]
}

after that you can simply import it import pinoClf from "pino-clf.custom";

This is a very basic implementation, and recommend researching if you desire something more complex. Of course there is more than one way to solve a problem but, I hope this helped. Cheers.

  • Related