Node.js 全局变量和 TypeScript [英] Node.js global variable and TypeScript
问题描述
我需要一些强类型的全局变量.
I need to have some strongly-typed global variables.
如此处所述:在 node.js 中扩展 TypeScript 全局对象,为了向 global
变量添加字段,我需要添加一个 .d.ts 文件,该文件扩展在 node.d.ts 中指定的 Global
接口.
As mentioned here: Extending TypeScript Global object in node.js, in order to add fields to the global
variable I need to add a .d.ts file that extends the Global
interface that's specified in node.d.ts.
此外,正如 Basarat 提到的:
Also, as Basarat mentioned:
您的文件需要清除任何根级别的导入或导出.那会将文件转换为模块并将其与全局断开连接类型声明命名空间.
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.
现在,我需要在 Global
接口上有字段,其类型是我创建的自定义接口:
Now, I need to have fields on the Global
interface whose types are custom interfaces that I created:
declare namespace NodeJS{
interface Global {
foo: Foo
bar: Bar
}
}
我非常不愿意使用 any
类型.
I'm extremely not willing to use the any
type.
我可以将所有接口声明移动/复制到这个声明文件中,但这对我来说是一个糟糕的解决方案,因为 Foo 和 Bar 反过来聚合了其他接口的许多字段,包括第三方接口,如 Moment 等.
I can move/copy all the interface declarations to this declaration file, but it's a bad solution for me, since both Foo and Bar in turn, aggregate many fields of other interfaces, including third party interfaces like Moment etc.
我需要一个解决这个悖论的方法
I need a solution for this paradox
推荐答案
这是一个方法.我不知道这是否是正确"的做事方式,但它适用于 TypeScript 3.7.4.
Here's an approach. I don't know if this is the 'correct' way of doing things, but it works for me with TypeScript 3.7.4.
- 假设您的源文件位于文件夹
src
中,创建一个新文件夹src/types
并创建一个文件global.d.ts
在此文件夹中. - 使用以下策略之一编写您的声明:
- 如果需要将外部类型导入到声明文件中,请使用以下语法:
- Assuming your source files live in a folder
src
, create a new foldersrc/types
and create a fileglobal.d.ts
in this folder. - Author your declarations using one of the following strategies:
- If you need to import external types into your declaration file, use the following syntax:
import { Express } from 'express';
declare global {
namespace NodeJS {
interface Global {
__EXPRESS_APP__: Express;
}
}
}
- 如果您的声明文件不包含任何导入,则上述方法将不起作用,您需要改用以下语法:
declare namespace NodeJS {
interface Global {
__CONNECTION_COUNT__: number;
}
}
- 确保您的
global.d.ts
文件(以及您可能添加到src/types
的任何其他文件)被 TypeScript 编译器选中,方法是添加跟随您的tsconfig.json
文件:
- Make sure your
global.d.ts
file (and any other files you might add tosrc/types
) is picked up by the TypeScript compiler, by adding the following to yourtsconfig.json
file:
{
"paths": {
"*": ["node_modules/*", "src/types/*"]
}
}
- 在代码中照常使用全局变量.
// Below, `app` will have the correct typings
const app = global.__EXPRESS_APP__;
这篇关于Node.js 全局变量和 TypeScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!