在node.js中扩展TypeScript Global对象

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

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

TypeScript编译器不喜欢这样做,因为Globaltypes没有名为myConfig对象:

TS2339:“全局”types中不存在属性“myConfig”。

我不想这样做:

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

我该如何扩展Globaltypes来包含myConfig或者告诉TypeScriptclosures并相信我? 我更喜欢第一个。

我不想更改node.d.ts的声明。 我看到这个SOpost,并试图这样做:

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

作为扩展现有Global接口的一种方式,但它似乎没有任何效果。

我看到这个SOpost,并试图这样做:

你可能有像vendor.d.ts这样的东西:

 // some import // AND/OR some export declare module NodeJS { interface Global { spotConfig: any } } 

您的文件需要清除任何根级别的importexports 。 这会将文件转换为模块,并将其从全局types声明命名空间中断开。

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

为了避免Typescript声明如下:

TS2339:“全局”types中不存在属性“myConfig”。

我build议定义自定义types。 我在我的项目中的src/types/custom.d.ts文件下执行:

 declare global { namespace NodeJS { interface Global { myConfig: { a: number; b: number; } } } } 

然后我确保这些在tsconfig.json文件中被Typescript考虑:

 { ... "files": [ ... "src/types/custom.d.ts" ] } 

现在您可以安全地使用自定义属性:

 console.log(global.myConfig.a); 

把下面的文件放到我们项目的根目录下工作。

global.d.ts

 declare namespace NodeJS { export interface Global { myConfig: any } } 

我们使用"@types/node": "^7.0.18"和TypeScript Version 2.3.4 。 我们的tsconfig.json文件如下所示:

 { "compilerOptions": { "module": "commonjs", "target": "es6" }, "exclude": [ "node_modules" ] }