gianpi
gianpi

Reputation: 3210

Typescript declaration file for an external npm package - constructor

I am using ES6 and Typescript for my Node project, however one library is a commonjs library. For that library, I created my own .d.ts declaration file:

module "@alpacahq/alpaca-trade-api" {
   export interface AlpacaParams { ... }

   // ...

   export class Alpaca implements Broker {

      // ...
      constructor(params: AlpacaParams);
   }

   export default Alpaca;
}

Everything works as expected, but I'm having a problem with the constructor.

If I use that class from within my project, and I try this:

this.alpaca = new Alpaca.Alpaca({...});

I get told that Alpaca.Alpaca is not a constructor. The only way it seems to work is if I do:

this.alpaca = new Alpaca.default({...});

I'm quite new to Typescript, so I'm sure I'm doing something wrong. Any ideas? The latter works, so I'm not blocked in my work, but I would like to set things up properly.

Thank you!

Edited to show TS config and imports

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "es6",
    "lib": ["es6", "es5"],
    "sourceMap": true,
    "outDir": "dist",
    "rootDir": "src",
    "strict": true,
    "moduleResolution": "node",
    "typeRoots": ["./types"],
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
} 

This is how I import it. Couldn't figure out how to make it work otherwise. If I import modules ES6 style, it breaks unless I use commonjs. If I use commonjs, I get an "export undefined" error.

import * as Alpaca from '@alpacahq/alpaca-trade-api';

Upvotes: 0

Views: 524

Answers (1)

Brian Burton
Brian Burton

Reputation: 3842

The problem is that you're importing all named exports with import * meaning that Alpaca refers to the module and .default refers to the exported class. Instead you should be importing just the default member.

Change your import to look like this:

// Import default member from module
import Alpaca from '@alpacahq/alpaca-trade-api';

this.alpaca = new Alpaca({...});

Upvotes: 1

Related Questions