Home > Back-end >  TypeScript global variable is not defined, declared in declare global{}
TypeScript global variable is not defined, declared in declare global{}

Time:12-17

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.

If this is in JavaScript (NodeJS), it would look like this:

// index.js
globalThis.helloWorld = 'Hello World!';
require('./log.js')

// log.js
console.log(helloWorld);

// output
Hello World!

What I'm struggling against in 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. Where did I go wrong?

CodePudding user response:

The fact it's a runtime error (ReferenceError) tells you this isn't a TypeScript problem. The problem is that the GLOBAL_EVENTS.on(...) code is running before the globalThis.GLOBAL_EVENTS = new EventEmitter(); code in app.ts, so GLOBAL_EVENTS (although defined in TypeScript) doesn't exist yet at runtime.

You need to make sure app.ts runs first, before the other file, so GLOBAL_EVENTS gets created before being used.

(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.)

  • Related