如何为替换 "exports" 对象的模块创建 Typescript (1.8) 类型定义?
How do I create a Typescript (1.8) Type Definition for a module that replaces the "exports" object?
我正在尝试为用匿名函数替换 module.exports 的模块创建类型定义。所以,模块代码是这样做的:
module.exports = function(foo) { /* some code */}
要在 JavaScript(节点)中使用模块,我们这样做:
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");
编辑: 为清楚起见,根据正确答案,我的最终代码如下所示:
模块.d.ts
declare module "theModule" {
function main(foo: string): string;
export = main;
}
模块-test.ts
import theModule = require("theModule");
theModule("foo");
这将转译为 the-module-test.js
const theModule = require("theModule");
theModule("foo");
对于导出函数的节点样式模块,use export =
function theModule(foo: string): string;
export = theModule;
我正在尝试为用匿名函数替换 module.exports 的模块创建类型定义。所以,模块代码是这样做的:
module.exports = function(foo) { /* some code */}
要在 JavaScript(节点)中使用模块,我们这样做:
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");
编辑: 为清楚起见,根据正确答案,我的最终代码如下所示:
模块.d.ts
declare module "theModule" {
function main(foo: string): string;
export = main;
}
模块-test.ts
import theModule = require("theModule");
theModule("foo");
这将转译为 the-module-test.js
const theModule = require("theModule");
theModule("foo");
对于导出函数的节点样式模块,use export =
function theModule(foo: string): string;
export = theModule;