網站搜尋

node.js - 我如何為一個取代「exports」對象的模組建立 TypeScript (1.8) 型別定義?


我正在嘗試為一個將 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");

答案#1

對於導出函數的 Node 風格模組,使用 export =

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