【问题标题】:How to write a typescript definition file for a node module that exports a function?如何为导出函数的节点模块编写打字稿定义文件?
【发布时间】:2014-07-24 15:11:04
【问题描述】:

考虑一下,对于 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()' 语句给 modules 起别名。尝试调用:

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

结果:

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

那么,您将如何为此编写定义文件?

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

...也是的,我知道你可以通过使用声明破坏类型系统来做到这一点,但我试图避免这种情况:

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

【问题讨论】:

    标签: typescript commonjs


    【解决方案1】:

    使用export =

    定义:

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

    用法(esModuleInterop enabled):

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

    【讨论】:

    • 在 TypeScript 2 中,这给了我以下错误:error TS2306: File 'glob.d.ts' is not a module. :(
    • 我使用的是 TS 版本 2.6.2,它适用于我。谢谢!
    • 如何指定具有属性的导出函数。例如:github.com/Schoonology/weighted/blob/master/lib/…?
    【解决方案2】:

    Basarat 的回答不适用于 typescript 2.1.5。你需要用export =声明函数和导出:

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

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

    【讨论】:

    • Basarat 的回答对我有用,我使用的是 2.6.2 版
    猜你喜欢
    • 2017-06-13
    • 2014-07-07
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    • 2017-02-21
    相关资源
    最近更新 更多