trusktr
trusktr

Reputation: 45504

How do we declare import types from NPM library that has no declaration files?

For example, if I have the following in my app,

import Node from 'infamous/motor/Node'
console.log(Node)

that works just fine. But the moment I actually do something with it,

import Node from 'infamous/motor/Node'
console.log(new Node)

then TypeScript will complain because there's no type definition for Node. How do I define the type of Node?

The library has no type declarations of it's own. I tried something like

import MotorNode from 'infamous/motor/Node'

declare class MotorNode {}
console.log(' --- ', new MotorNode)

but I get the error

./src/app.tsx(6,8): error TS2440: Import declaration conflicts with local declaration of 'MotorNode'

Upvotes: 0

Views: 557

Answers (1)

Louis
Louis

Reputation: 151511

When I need to do what you are trying to do, I create an externals.d.ts file in which I put module augmentations for my project and make sure that my tsconfig.json includes it in the compilation.

In your case the augmentation might look something like this:

declare module "infamous/motor/Node" {
  class Node {
    // Whatever you need here...
  }

  export default Node;
}

I put it in a separate file because a module augmentation like this has to be global (must be outside any module), and a file that contains a a top-level import or export is a module. (See this comment from a TypeScript contributor.)

Upvotes: 2

Related Questions