2

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?

0

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

"you need to make sure app.ts runs first" ... it would be nice if someone indicated how to do this.
@LeeMeador - That's largely project-specific. In general, you define the entry point of your program -- you tell Node.js where to start on the node yourEntryPointHere.js line (and on browsers you specify the entry point in the HTML script tag). That entry point needs to execute the code creating the globals before the code using them. But again, the better way to do this is to use modules, since module imports/exports define the graph of which modules depend on which others, and the JavaScript engine can then execute the dependencies before the modules that depend on them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.