NodeJS allows you to set process-level global values that can be accessed in any module.

In general I would consider implicitly sharing global values between modules a bad practice, however in certain situations it can be a pragmatic choice.

Assigning globals using pure JavaScript is straightforward, making them work with TypeScript is another thing. Let’s dive in.

# NodeJS globals in JavaScript

Setting a global value in NodeJS couldn’t be simpler:

# NodeJS globals in TypeScript

Note: Make sure that you have @types/node installed.

Let’s start by trying to just assign the value and see what happens:

If we look at the type of global it’s NodeJS.Global. Fortunately TypeScripts declaration merging allows us to extend this interface to include our new attribute:

This declaration can be placed in any .ts file in your project. Just make sure that it is imported and the global value is assigned before any other module would use it.

One use case remains though:

This error is type level only as the value should be available in the runtime already. To fix it we can just declare it in the global scope as well.

Note that the global scope and NodeJS global object are two different things from TypeScripts point of view, hence the duplicated declaration. global is actually a variable declared in the global scope.

# Final thoughts

You may wonder if it makes sense to use an implicit global instead of just importing the value explicitly.

I don’t think there is one answer to that. For example, in my case, using the implicit log from example above felt smoother than having to import it every time when I wanted to log something, even with IDE automated imports. I feel that this made me use log more often which led to slightly better quality of application logs. It can also remove the headache of constantly adding and removing the import statement if it turns out that the last log was removed and linter throws errors at you that it is no longer needed. Also having the globals explicitly typed, with clear lifecycle doesn’t make them look like a hack.

Just keep in mind that abusing global can lead to a codebase that is both hard to read and reason about.