在node.js中扩展TypeScript全局对象 [英] Extending TypeScript Global object in node.js
问题描述
我有一个node.js应用程序,该应用程序将一些配置信息附加到global
对象:
I have a node.js app that attaches some config information to the global
object:
global.myConfig = {
a: 1,
b: 2
}
TypeScript编译器不喜欢这样,因为Global
类型没有名为myConfig
的对象:
The TypeScript compiler doesn't like this because the Global
type has no object named myConfig
:
TS2339:类型'Global'上不存在属性'myConfig'.
TS2339: Property 'myConfig' does not exist on type 'Global'.
我不想这样做:
global['myConfig'] = { ... }
如何将Global
类型扩展为包含myConfig
或只是告诉TypeScript关闭并信任我?我希望第一个.
How do I either extend the Global
type to contain myConfig
or just tell TypeScript to shut up and trust me? I'd prefer the first one.
我不想更改node.d.ts
中的声明.我看到了此 SO帖子,并尝试了以下方法:
I don't want to change the declarations inside node.d.ts
. I saw this SO post and tried this:
declare module NodeJS {
interface Global {
myConfig: any
}
}
作为扩展现有Global
接口的一种方法,但是似乎没有任何作用.
as a way to extend the existing Global
interface, but it doesn't seem to have any effect.
推荐答案
我看到了这样的帖子并尝试过:
I saw this SO post and tried this:
您可能有类似vendor.d.ts
的内容:
// some import
// AND/OR some export
declare module NodeJS {
interface Global {
spotConfig: any
}
}
您的文件需要任何根级别import
或exports
的干净.这样会将文件转换为模块,并将其与全局类型声明名称空间断开连接.
Your file needs to be clean of any root level import
or exports
. That would turn the file into a module and disconnect it from the global type declaration namespace.
更多: https://basarat.gitbooks.io/typescript/content/docs/project/modules.html
这篇关于在node.js中扩展TypeScript全局对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!