在node.js中扩展TypeScript全局对象 [英] Extending TypeScript Global object in node.js

查看:849
本文介绍了在node.js中扩展TypeScript全局对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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
    }
}

您的文件需要任何根级别importexports干净.这样会将文件转换为模块,并将其与全局类型声明名称空间断开连接.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆