Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of module.exports in Typescript Declaration file

Tags:

typescript

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();
like image 779
Tuizi Avatar asked Jan 06 '17 00:01

Tuizi


People also ask

Does module exports work in TypeScript?

TypeScript supports export = to model the traditional CommonJS and AMD workflow. The export = syntax specifies a single object that is exported from the module. This can be a class, interface, namespace, function, or enum.

What is declare module in TypeScript?

A module is a piece of code that can be called or used in another code. There is nothing new about modules in Typescript. The concept of the module was introduced by JavaScript with ECMAScript 2015 release. Typescript is just re-using this feature.

How do you identify a ts file as a module?

In TypeScript, files containing a top-level export or import are considered modules.

Is module exports the same as export?

When we want to export a single class/variable/function from one module to another module, we use the module. exports way. When we want to export multiple variables/functions from one module to another, we use exports way.


1 Answers

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.';
like image 158
Cameron Tacklind Avatar answered Sep 30 '22 09:09

Cameron Tacklind