首页 文章

如何为导出函数的节点模块编写打字稿定义文件?

提问于
浏览
9

考虑一下,对于toml节点模块,我可以简单地使用:

// 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');
toml.parse(...);

但是,如果节点模块只导出单个函数,例如'glob'(https://github.com/isaacs/node-glob) .

该模块的节点用法是:

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

你天真地期望你能做到这一点:

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

...但是因为typescripts 'import'语义有点奇怪,所以看起来你只能使用'import .. = require()'语句来对模块进行别名 . 试着打电话:

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

结果是:

error TS2072: Module cannot be aliased to a non-module type.

那么,你会如何为此编写定义文件?

NB . 请注意,这是针对使用节点的commonjs模块,而不是AMD模块 .

...也是的,我知道你可以通过使用declare打破类型系统来做到这一点,但我试图避免这样做:

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

2 回答

  • 2

    使用 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) => { });
    
  • 11

    Basarat 's answer doesn'吨使用打字稿2.1.5 . 您需要使用 export = 声明函数和导出:

    export = MyFunction;
    declare function MyFunction(): string;
    

    How to write a definition file for commonjs module that exports function

相关问题