Search code examples
typescriptcommonjs

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


Consider, 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 node module that export only a single function, such as 'glob' (https://github.com/isaacs/node-glob).

The node usage of this module would be:

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

You'd naively expect you could do this:

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

...but because typescripts 'import' semantics are a bit strange, it seems you can only use the 'import .. = require()' statement to alias modules. Trying 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. Notice that this is for a commonjs module using node, not an AMD module.

...also yes, I know you can do this by breaking the type system using declare, but I'm trying to avoid that:

declare var require;
var glob = require('glob');
glob(...); 

Solution

  • Use export =.

    Definition:

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

    Usage (with esModuleInterop enabled):

    import glob from 'glob';
    glob("*.js", {}, (err, files) => { });