Aleksandar Djindjic
Aleksandar Djindjic

Reputation: 181

How to write a definition file for commonjs module that exports function

I want to use simple commonjs module in typescript, and here are 3 files

original lib:

//commonjs-export-function.js
module.exports = function() {
    return 'func';
};

definition file:

//commonjs-export-function.d.ts
declare function func(): string;
export = func;

typescript program which use it:

//main.ts
import { func } from './commonjs-function';

console.log(func());

When I run tsc I get this error:

tsc main.ts && node main.js
main.ts(1,22): error TS2497: Module '"/Users/aleksandar/projects/typescript-playground/commonjs-function"' resolves to a non-module entity and cannot be imported using this construct.

here is also already answered question but it doesn't work with typescript 2.0

How to write a typescript definition file for a node module that exports a function?

Upvotes: 9

Views: 4100

Answers (3)

zurik_ned
zurik_ned

Reputation: 1

for CommonJS use module.exorts = variable_name

for es2015 use export default const/let variable_name OR variable defination

export default variable_name

Upvotes: 0

kohlmannj
kohlmannj

Reputation: 31

I've recently had trouble finding examples of CommonJS module definitions compatible with TypeScript 2.8.x. Here's an attempt to demonstrate the approach using map-promise-limit, a package with a single CommonJS export:

declare module 'promise-map-limit' {

  type IIteratee<T, R> = (value: T) => Promise<R> | R;

  function mapLimit<T, R>(
    iterable: Iterable<T>,
    concurrency: number,
    iteratee: IIteratee<T, R>
  ): Promise<R[]>;

  export = mapLimit;

}

In summary, to create a type definition for a CommonJS module with a single function-type export:

  • Use the same declare module syntax as you'd use for any other ambient module
  • Declare a named function (without using the declare keyword) within the module body
  • Export the function with export = instead of export default

[Edit] Realized this is similar to basarat's answer here. Good deal!

Upvotes: 3

Aleksandar Djindjic
Aleksandar Djindjic

Reputation: 181

I found the solution in typescript docs here: http://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-function-d-ts.html

*~ Note that ES6 modules cannot directly export callable functions.
*~ This file should be imported using the CommonJS-style:
*~   import x = require('someLibrary');
...
export = MyFunction;
declare function MyFunction(): string;

so mu definition file should be:

//commonjs-export-function.d.ts
declare function func(): string;
export = func;

and import with require:

//main.ts
import func = require('./commonjs-export-function');

Upvotes: 6

Related Questions