3

I'm using third-party library with separate @types definition that looks like this:

declare namespace Foo { /* ... */ }

declare class Foo { /* ... */ }

export = Foo;

How can I import the class Foo in my code?

Also, is this such weird name duplication a good practice in Typescript? (Here's the actual definition file I'm using).

Max Yankov
  • 12,551
  • 12
  • 67
  • 135

3 Answers3

2

Your class is a constructor function. They will essentially merge as the namespaced objects are appended to the constructor function definition and you will have something like nested classes. If you want to import only the Foo class, then you tricked yourself.

I can't say if it's good practice or not, but I use it to emulate nested classes.

The namespace and class can be imported by using:

import * as Foo from 'foo';
SparK
  • 5,181
  • 2
  • 23
  • 32
  • I'm OK with importing everything, I just can't figure out how do I use this class at all. – Max Yankov Jul 17 '19 at 14:26
  • Oh, `import * as Foo from 'foo'` – SparK Jul 17 '19 at 19:41
  • It did not help me to resolve the issue in my Angular library: when I consume the library in my Angular app - I keep getting the error saying that I am trying to use a namespace (instead of a class). – Alexander May 10 '22 at 16:56
1

I solved it by using this let foo: InstanceType<typeof Foo>

Raza
  • 3,147
  • 2
  • 31
  • 35
0

Add "esModuleInterop": true to the compiler options in your tsconfig.json file.

Then import as normal:

import TelegramBot from 'node-telegram-bot-api';

const foo = new TelegramBot();
Ryan W.
  • 41
  • 4
  • I've tried that before posting the question, obviously. `Module '".../node_modules/@types/node-telegram-bot-api/index"' can only be default-imported using the 'esModuleInterop' flag`. And I deliberately changed the names to Foo in context of this question for better readability. – Max Yankov Jul 17 '19 at 16:40
  • You need to add ```"esModuleInterop": true``` to the compiler options in your tsconfig.json – Ryan W. Jul 17 '19 at 18:30
  • @RyanW. it's clear that it's an option, but given the fact that I don't import an ES module but, with type declarations, a typescript module, it does not seem as a correct option, but just a hack. – Max Yankov Jul 18 '19 at 00:04