Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(...); 
like image 682
Doug Avatar asked Jun 04 '14 05:06

Doug


People also ask

How do you make a export function in TypeScript?

Use named exports to export a function in TypeScript, e.g. export function sum() {} . The exported function can be imported by using a named import as import {sum} from './another-file' . You can use as many named exports as necessary in a single file.

Can we export function in TypeScript?

Yes, we can export the functions in TypeScript by using the 'export' keyword at the start of the function.

Does module exports work in TypeScript?

TypeScript supports export = to model the traditional CommonJS and AMD workflow. The export = syntax specifies a single object that is exported from the module. This can be a class, interface, namespace, function, or enum.


1 Answers

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) => { });
like image 111
basarat Avatar answered Oct 16 '22 14:10

basarat