在 node.js 中扩展 TypeScript Global 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35074713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:50:50  来源:igfitidea点击:

Extending TypeScript Global object in node.js

node.jstypescriptglobal

提问by d512

I have a node.js app that attaches some config information to the globalobject:

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

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

The TypeScript compiler doesn't like this because the Globaltype has no object named myConfig:

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

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

TS2339:“全局”类型上不存在属性“myConfig”。

I don't want to do this:

我不想这样做:

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

How do I either extend the Globaltype to contain myConfigor just tell TypeScript to shut up and trust me? I'd prefer the first one.

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

I don't want to change the declarations inside node.d.ts. I saw this SO postand tried this:

我不想改变里面的声明node.d.ts。我看到了这个SO 帖子并尝试了这个:

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

as a way to extend the existing Globalinterface, but it doesn't seem to have any effect.

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

回答by basarat

I saw this SO post and tried this:

我看到了这个 SO 帖子并尝试了这个:

You probably have something like vendor.d.ts:

你可能有这样的事情vendor.d.ts

// some import 
// AND/OR some export

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

Your file needs to be cleanof any root level importor exports. That would turn the file into a moduleand disconnect it from the global type declaration namespace.

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

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

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

回答by Nik Sumeiko

To avoid Typescript claim something like this:

为了避免打字稿声称这样的事情:

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

TS2339:“全局”类型上不存在属性“myConfig”。

I suggest to define custom types. I do it under src/types/custom.d.tsfile in my project:

我建议定义自定义类型。我src/types/custom.d.ts在我的项目中的文件下做:

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

Then I ensure these are considered by Typescript in tsconfig.jsonfile:

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

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

Now you're safe to use your custom property:

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

console.log(global.myConfig.a);

回答by Shaun Luttin

Putting the following file into our project's root directory worked.

将以下文件放入我们项目的根目录即可。

global.d.ts

global.d.ts

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

We're using "@types/node": "^7.0.18"and TypeScript Version 2.3.4. Our tsconfig.json file looks like this:

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

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

回答by Alexander Mills

The only thing that works for me is this:

唯一对我有用的是:

// lib/my.d.ts

import Global = NodeJS.Global;
export interface CDTGlobal extends Global {
  cdtProjectRoot: string
}

and then using it in other files like so

然后像这样在其他文件中使用它

import {CDTGlobal} from "../lib/my.d.ts";
declare const global: CDTGlobal;

const cwd = global.cdtProjectRoot; // works

回答by Benny Neugebauer

What worked for me is:

对我有用的是:

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

global.myConfig = 'it works!';

Only downside is when using it you will have to turn off the ESLint rule @typescript-eslint/no-namespace.

唯一的缺点是在使用它时你必须关闭 ESLint 规则@typescript-eslint/no-namespace

For completeness here is my tsconfig.json:

为了完整起见,这里是我的tsconfig.json

{
  "compilerOptions": {
    "declaration": true,
    "emitDecoratorMetadata": true,
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "forceConsistentCasingInFileNames": true,
    "jsx": "react",
    "lib": ["dom", "es2017"],
    "module": "commonjs",
    "moduleResolution": "node",
    "noEmitOnError": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "outDir": "dist",
    "removeComments": true,
    "resolveJsonModule": true,
    "rootDir": "src",
    "sourceMap": true,
    "strict": true,
    "target": "es6"
  },
  "exclude": ["dist", "node_modules"]
}

回答by edvard chen

Copy my answer of another post:

复制我在另一篇文章中的回答:

globalThisis the future.

全球这是未来。

// Way 1
var abc: number
globalThis.abc = 200 // no error

// Way2
declare var age: number
globalThis.age = 18 // no error