[英]TypeScript global variable is not defined, declared in declare global{}
I'm trying to add a global scope variable (which means it can be accessed from anywhere without having to import/require it from another file) in TypeScript.我正在尝试在 TypeScript 中添加一个全局 scope 变量(这意味着它可以从任何地方访问,而无需从另一个文件导入/需要它)。
If this is in JavaScript (NodeJS), it would look like this:如果这是在 JavaScript (NodeJS) 中,它看起来像这样:
// index.js
globalThis.helloWorld = 'Hello World!';
require('./log.js')
// log.js
console.log(helloWorld);
// output
Hello World!
What I'm struggling against in TypeScript:我在 TypeScript 中遇到的问题:
// types.ts
// ...
declare global{
var GLOBAL_EVENTS: EventEmitter
}
// ...
// app.ts
// ...
globalThis.GLOBAL_EVENTS = new EventEmitter()
// ...
// usage in another file
// ...
GLOBAL_EVENTS.on(...)
// ...
// output:
ReferenceError: GLOBAL_EVENTS is not defined
I've tried using global.GLOBAL_EVENTS
too, but to no avail, it works.我也尝试过使用
global.GLOBAL_EVENTS
,但无济于事,它可以工作。 Where did I go wrong?我在哪里 go 错了?
The fact it's a runtime error ( ReferenceError
) tells you this isn't a TypeScript problem.这是一个运行时错误 (
ReferenceError
) 的事实告诉您这不是 TypeScript 问题。 The problem is that the GLOBAL_EVENTS.on(...)
code is running before the globalThis.GLOBAL_EVENTS = new EventEmitter();
问题是
GLOBAL_EVENTS.on(...)
代码在globalThis.GLOBAL_EVENTS = new EventEmitter();
之前运行。 code in app.ts
, so GLOBAL_EVENTS
(although defined in TypeScript) doesn't exist yet at runtime. app.ts
中的代码,因此GLOBAL_EVENTS
(尽管在 TypeScript 中定义)在运行时还不存在。
You need to make sure app.ts
runs first, before the other file, so GLOBAL_EVENTS
gets created before being used.您需要确保
app.ts
先运行,然后再运行其他文件,以便在使用之前创建GLOBAL_EVENTS
。
(This is one of the good reasons for not using globals and using an export from a module instead: Then the module system would ensure that module is loaded and ready before its exports are used.) (这是不使用全局变量而是使用模块导出的充分理由之一:然后模块系统将确保在使用其导出之前加载并准备好模块。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.