node.js - 在 node.js 中扩展 TypeScript 全局对象

标签 node.js typescript global

我有一个 node.js 应用程序,它将一些配置信息附加到 global 对象:

global.myConfig = {
    a: 1,
    b: 2
}

TypeScript 编译器不喜欢这样,因为 Global 类型没有名为 myConfig 的对象:

TS2339: Property 'myConfig' does not exist on type 'Global'.

我不想这样做:

global['myConfig'] = { ... }

如何扩展 Global 类型以包含 myConfig 或只是告诉 TypeScript 闭嘴并信任我?我更喜欢第一个。

我不想更改 node.d.ts 中的声明。我看到了 SO post并尝试了这个:

declare module NodeJS  {
    interface Global {
        myConfig: any
    }
}

作为对现有Global接口(interface)的一种扩展方式,但似乎没有任何作用。

最佳答案

I saw this SO post and tried this:

你可能有类似 vendor.d.ts:

// some import 
// AND/OR some export

declare module NodeJS  {
    interface Global {
        spotConfig: any
    }
}

您的文件需要是clean 任何根级别的importexports。这会将文件变成一个模块,并断开它与全局类型声明命名空间的连接。

更多:https://basarat.gitbooks.io/typescript/content/docs/project/modules.html

关于node.js - 在 node.js 中扩展 TypeScript 全局对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35074713/

相关文章:

javascript - 将逗号分隔的数字字符串转换为数字

typescript - 强制 TypeScript 在悬停时显示变量的最终状态

C# 更改全局鼠标光标

你能在另一个文件中 extern #define 变量吗?

typescript - 在 typescript 中 Jest mock express 和 Mongoose

C# - 类对象的命名空间范围实例

node.js - Node 表达+强大+带有multipart/form-data的表单如何获取req.body?

mysql - 如何简化node js查询中的嵌套if循环

node.js - 可以将 Visual Studio Code 配置为使用 nodemon 启动吗

javascript - 为什么 typescript 不提示某些 undefined variable