0

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';
4
  • 1
    Can you post your Typescript config and the way you import this module into your application code? There are a few combinations of choices there than can affect how the import works. Commented Jan 16, 2021 at 21:57
  • Sure, added to the original message! Commented Jan 17, 2021 at 0:05
  • sometimes just restart TS Server will resolve. Commented Jan 22, 2021 at 4:03
  • I restarted everything several times, that's not the issue, unfortunately. Commented Jan 24, 2021 at 0:09

1 Answer 1

1
+50

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({...});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that was it! I think I tried this first, but then I had a mistake in the module resolution setting, then when I fixed that, I didn't think to change the import back.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.