如何让 TypeScript 知道附加到全局命名空间的函数

How to let TypeScript know about a function attached the the global namespace

我很好地掌握了 TypeScript 并经常使用它,所以我知道如何做大多数事情。

假设我有一个附加到 global 的函数,例如 getThisOrThat() 是事件。此函数附加到全局,但它也是项目 node_modules 中模块的一部分。它具有完美的类型,但由于该模块不直接导出函数(请记住它们附加到全局)。

所以现在我不能做 import { getThisOrThat } from 'the-module'; 因为转译的是:

module.getThisOrThat() /// crash and burn cause it's on global :)

我也不能 require() 模块,因为它在转译时当然是一样的。

要通过我目前知道的编译器有两种选择。

这两个都可以通过编译器检查,但我真的想让整个项目都受益于此模块的全局函数类型。我也试过用 <ref /> 添加它,但没有成功。

所以你有在模块中声明一些函数的类型,但在运行时你想像使用全局函数一样使用它?然后你可以添加你自己的 d.ts 文件 augments global namespace:

declare module 'the-module-global' {

import * as TheModule from 'the-module';// this import is used for typechecking only

global {
    var getThisOrThat : typeof TheModule.getThisOrThat;
}

}