【问题标题】:How do I create a Typescript (1.8) Type Definition for a module that replaces the "exports" object?如何为替换“导出”对象的模块创建 Typescript (1.8) 类型定义?
【发布时间】:2016-09-10 16:14:36
【问题描述】:

我正在尝试为将 module.exports 替换为匿名函数的模块创建类型定义。所以,模块代码是这样做的:

module.exports = function(foo) { /* some code */}

要在 JavaScript (Node) 中使用该模块,我们这样做:

const theModule = require("theModule");
theModule("foo");

我已经编写了一个 .d.ts 文件来执行此操作:

export function theModule(foo: string): string;

然后我可以像这样编写一个 TypeScript 文件:

import {theModule} from "theModule";
theModule("foo");

当我转译成 JavaScript 时,我得到:

const theModule_1 = require("theModule");
theModule_1.theModule("foo");

我不是模块作者。所以,我无法更改模块代码。

如何编写我的类型定义,以便正确转换为:

const theModule = require("theModule");
theModule("foo");

编辑:为清楚起见,根据正确答案,我的最终代码如下所示:

the-module.d.ts

declare module "theModule" {
    function main(foo: string): string;
    export = main;
}

the-module-test.ts

import theModule = require("theModule");
theModule("foo");

将转译为 the-module-test.js

const theModule = require("theModule");
theModule("foo");

【问题讨论】:

    标签: node.js module typescript definitelytyped


    【解决方案1】:

    对于导出函数的节点样式模块,use export =

    function theModule(foo: string): string;
    export = theModule;
    

    【讨论】:

      猜你喜欢
      • 2014-02-16
      • 2016-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-17
      • 1970-01-01
      • 2020-06-27
      • 2023-02-23
      相关资源
      最近更新 更多