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.
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(...);
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.
Yes, we can export the functions in TypeScript by using the 'export' keyword at the start of the function.
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.
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) => { });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With