我正在尝试为模块创建类型定义,以匿名函数替换 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 样式模块,use export =
function theModule(foo: string): string;
export = theModule;
关于node.js - 如何为替换 "exports"对象的模块创建 Typescript (1.8) 类型定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37227386/