Doug Doug - 1 year ago 92
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;


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

However, what about node module that export only a single function, such as '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');

Answer Source

Use export =.


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


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

import glob = require('glob');
glob("*.js", {}, (err, files) => { });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download