Doug Doug - 2 months ago 8
TypeScript Question

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(...);

Answer

Use export =.

Definition:

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

Usage:

/// <reference path="glob.d.ts"/>

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