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

We believe that for the toml node module I can simply use:

// toml.d.ts declare module TOML { export function parse(value:string):any; } declare module "toml" { export = TOML; } 

Then:

 /// <reference path="../../../../../defs/toml/toml.d.ts"/> import toml = require('toml'); toml.parse(...); 

However, what about the node module, which exports only one function, such as 'glob' ( https://github.com/isaacs/node-glob ).

Using this node module:

 var glob = require("glob") glob("*.js", {}, callback(err, files) { ... }); 

You would naively expect to be able to do this:

 // glob.d.ts declare function globs(paths:string, options:any, callback:{(err:any, files:string[]):void; 

... but since the semantics of import imports are a little strange, it seems you can use the import ... = require () operator for alias modules. Attempt to call:

 /// <reference path="../../../../../defs/glob/glob.d.ts"/> import blog = require('glob'); 

Results in:

 error TS2072: Module cannot be aliased to a non-module type. 

So, how would you write a definition file for this?

NB. Note that this is for the commonjs module using node, not the AMD module.

... also yes, I know that you can do this by breaking the type system with a declaration, but I try to avoid this:

 declare var require; var glob = require('glob'); glob(...); 
+7
commonjs typescript
source share
2 answers

Use export = .

Definition:

 // glob.d.ts declare module 'glob' { function globs(paths: string, options: any, callback: (err: any, files: string[]) => void); export = globs; } 

Using:

 /// <reference path="glob.d.ts"/> import glob = require('glob'); glob("*.js", {}, (err, files) => { }); 
+9
source share

Basarat answer does not work with typescript 2.1.5. You need to declare a function and export using export = :

 export = MyFunction; declare function MyFunction(): string; 

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

+1
source share

All Articles