Tuizi
Tuizi

Reputation: 1673

Equivalent of module.exports in Typescript Declaration file

I try to do the declaration file of a library.

In the library.js file there is:

if (typeof module !== 'undefined' /* && !!module.exports*/) {
    module.exports = Library;
}

What should I put in my library.d.ts file to be able to import and use this library in my code?

I expect to be able to do:

import { Library } from 'library';
const instance = new Library();

Upvotes: 10

Views: 11140

Answers (2)

Cameron Tacklind
Cameron Tacklind

Reputation: 7184

You need to use the special export = and import Library = require syntax, as pointed out by @Nitzan:

export = and import = require()


A complete example:

node_modules/library/index.js

module.exports = function(arg) {
  return 'Hello, ' + arg + '.';
}

library.d.ts This filename technically does not matter, only the .d.ts extension.

declare module "library" {
  export = function(arg: string): string;
}

source.ts

import Library = require('library');

Library('world') == 'Hello, world.';

Upvotes: 8

Nitzan Tomer
Nitzan Tomer

Reputation: 164129

You must use this syntax in the case of export =:

import Library = require("library");

More about it here: export = and import = require()

Upvotes: 2

Related Questions