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.

  1. Assuming your source files live in a folder src, create a new folder src/types and create a file global.d.ts in this folder.
  2. 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;
    }
  }
}
  • If your declaration file does not contain any imports, the above will not work, and you'll need to use this syntax instead:
declare namespace NodeJS {
  interface Global {
    __CONNECTION_COUNT__: number;
  }
}
  1. Make sure your global.d.ts file (and any other files you might add to src/types) is picked up by the TypeScript compiler, by adding the following to your tsconfig.json file:
{
  "paths": {
    "*": ["node_modules/*", "src/types/*"]
  }
}
  1. Use the global variable as normal inside your code.
// Below, `app` will have the correct typings
const app = global.__EXPRESS_APP__;
Answer from Tom Spencer on Stack Overflow
Top answer
1 of 4
13

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.

  1. Assuming your source files live in a folder src, create a new folder src/types and create a file global.d.ts in this folder.
  2. 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;
    }
  }
}
  • If your declaration file does not contain any imports, the above will not work, and you'll need to use this syntax instead:
declare namespace NodeJS {
  interface Global {
    __CONNECTION_COUNT__: number;
  }
}
  1. Make sure your global.d.ts file (and any other files you might add to src/types) is picked up by the TypeScript compiler, by adding the following to your tsconfig.json file:
{
  "paths": {
    "*": ["node_modules/*", "src/types/*"]
  }
}
  1. Use the global variable as normal inside your code.
// Below, `app` will have the correct typings
const app = global.__EXPRESS_APP__;
2 of 4
7

I found this works.

Have one file that declares the property on the NodeJS.Global interface with the any type. This file has to be clean of imports or refrences.

node.d.ts

declare namespace NodeJS{
    interface Global {
        foo: any
    }
}

Then in the second file you declare a global variable that has the correct type.

global.d.ts

import IFoo from '../foo'

declare global {

  const foo:Ifoo

}
🌐
Plain English
plainenglish.io › blog › typescript-and-global-variables-in-node-js-59c4bf40cb31
TypeScript and Global Variables in Node.js
August 14, 2021 - Nodejs · Javascript · ByTomas Nilsson · •Published on2012-12-01 · Prerequisites: VSCode and TypeScript should be already installed. TL;DR — Here is a working project: emptyts. Create a file in the root of the project named global.d.ts with the following content. Please note: The use of var , it's required for this to work (see typescriptlang.org for information about this). Without the export {} , all variables will become any ·
Discussions

typescript - Declare global variable in NodeJS - Stack Overflow
Because the interface of the global namespace isn't the same as the interface of globalThis; the latter is a subset of the former. (You can have global variables that aren't properties of the global object, via global-scope let, const, and class.) They're defined distinctly in TypeScript. More on stackoverflow.com
🌐 stackoverflow.com
Extending TypeScript Global object in node.js - Stack Overflow
@basarat - RE: "Your file needs ... modifying module" here as per typescriptlang.org/docs/handbook/declaration-files/templates/… ? If I understand that example correctly, adding something along the lines of declare global { namespace NodeJS { ...... More on stackoverflow.com
🌐 stackoverflow.com
Create a global variable in TypeScript - Stack Overflow
Extend the other answer about globalThis (see MDN and TypeScript 3.4 note) with more specific examples (TypeScript only without mixing with JavaScript), as the behavior was fairly confusing. All examples are run under Nodejs v12.14.1 and TypeScript Version 4.2.3. More on stackoverflow.com
🌐 stackoverflow.com
global variables in nodejs

You probably shouldn't be using a global variable for what you're trying to do, but…

to let TypeScript know about your own properties on the global object you need to augment the Global interface in a d.ts file:

export interface Global {
 myProp: string;
}

If all you want is to 'share' stuff across files (i.e. modules) you probably want to export from your modules rather than add to the global object.

More on reddit.com
🌐 r/typescript
2
3
October 15, 2015
🌐
Reddit
reddit.com › r/typescript › global variables
r/typescript on Reddit: Global Variables
February 12, 2024 -

Hey guys.

Lately, I've been messing around with TypeScript. I come from a full JS background and I wanted to upgrade myself to TS in my spare time.

For context, I've created numerous APIs using Express with JS and I wanted to see if I can recreate those APIs but this time in TS.

However, I've run into a problem: how do you create global variables in TypeScript?

In a NodeJS environment I would normally just go:

// index.js

global.foo = "and I call it a day"

// controller.js

global.foo = "Modified by a different file."

How do I replicate this behavior in TypeScript?

I'm not asking if I should be using Global Variables, or should I reinvent my existing architecture to not use Global Variables; I just need to know how to do it. I've tried endlessly Googling this and while I've come close to finding a solution none of them seem to fit the bill.

For example: http://marcinbiernat.pl/2020/03/nodejs-globals/

This guy just has him declaring things and it works perfectly. The problem I have with it is: I don't want the declarations to clog up index.ts for example. How do I separate my declarations from my code? Is that even possible?

🌐
TypeScript
typescriptlang.org › docs › handbook › declaration-files › templates › global-d-ts.html
TypeScript: Documentation - Global .d.ts
A global library is one that can be accessed from the global scope (i.e. without using any form of import). Many libraries simply expose one or more global variables for use.
🌐
Plain English
plainenglish.io › blog › how-to-create-global-variables-in-typescript-with-node-js-9ca24f648991
How to Create Global Variables in TypeScript with Node.js
December 13, 2021 - Here we are declaring a global variable, interface and type, with this, all of them will be available everywhere in our project. And yes, unfortunately, we have to use var, otherwise, it won’t work. So far, so good, now if we want TypeScript to recognize our global variable, interface and type, we have to create a @types folder and put there our .d.ts file.
🌐
Blake Williams
blakewilliams.me › posts › using-ts-node-with-global-types
Using ts-node with Global Types | Blake Williams
September 7, 2020 - We can use declare to tell TypeScript that global contains a property with a given type. ... Now we’re able to set global.myGlobal in the application without type errors. Getting right into it with a contrived example, given a global.d.ts declaring a global variable, named myGlobal: declare const myGlobal: number namespace NodeJS { interface Global { myGlobal: number } }
🌐
JavaScript in Plain English
javascript.plainenglish.io › typescript-and-global-variables-in-node-js-59c4bf40cb31
TypeScript and Global Variables in Node.js | by Tomas Nilsson | JavaScript in Plain English
August 16, 2021 - So, avoid code that uses global variables at the root of the files. Or avoid it altogether. :) Example for Express follows: import "express";declare global { namespace Express { interface Request { token: string, UserID: string } } }export { }; More content at plainenglish.io · JavaScript · Programming · Typescript · Nodejs ·
Find elsewhere
🌐
Bobby Hadz
bobbyhadz.com › blog › typescript-declare-global-variable
How to declare Global Variables in TypeScript | bobbyhadz
To declare a global variable in TypeScript, create a .d.ts file and use declare global{} to extend the global object with typings for the necessary properties or methods.
🌐
Marcinbiernat
marcinbiernat.pl › 2020 › 03 › nodejs-globals
NodeJS globals and TypeScript · Marcin Biernat
March 22, 2020 - Setting a global value in NodeJS couldn’t be simpler: 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 globalThis. Fortunately TypeScripts declaration merging allows us to extend this interface to include our new attribute:
🌐
Stack Overflow
stackoverflow.com › questions › 69192564 › declare-global-variable-in-nodejs
typescript - Declare global variable in NodeJS - Stack Overflow
declare global { let LOG: Logger; } // eslint-disable-next-line @typescript-eslint/no-namespace declare namespace globalThis { let LOG: Logger; } globalThis.LOG = new Logger(); Yes, it works, but I need to declare it twice. Why? ... Just FWIW, I'd suggest exporting LOG from a module instead and importing it where you need it. Creating additional global variables is generally a not best practice.
🌐
Medium
returnofking04.medium.com › typescript-adding-types-for-global-variables-and-functions-5e2cb024f3d6
Typescript: adding types for global variables and functions | by Abhay | Medium
August 28, 2022 - In Typescript there is a concept of global variables which are defined at the start of the program and can be used anywhere in the program without any explicit import.
Top answer
1 of 16
176

globalThis is the future.

First, TypeScript files have two kinds of scopes

global scope

If your file hasn't any import or export line, this file would be executed in global scope that all declaration in it are visible outside this file.

So we would create global variables like this:

// xx.d.ts
declare var age: number

// or 
// xx.ts
// with or without declare keyword
var age: number

// other.ts
globalThis.age = 18 // no error

All magic come from var. Replace var with let or const won't work.

module scope

If your file has any import or export line, this file would be executed within its own scope that we need to extend global by declaration-merging.

// xx[.d].ts
declare global {
  var age: number;
}

// other.ts
globalThis.age = 18 // no error

You can see more about module in official docs

2 of 16
89

Inside a .d.ts definition file

type MyGlobalFunctionType = (name: string) => void

If you work in the browser, you add members to the browser's window context:

interface Window {
  myGlobalFunction: MyGlobalFunctionType
}

Same idea for NodeJS:

declare module NodeJS {
  interface Global {
    myGlobalFunction: MyGlobalFunctionType
  }
}

Now you declare the root variable (that will actually live on window or global)

declare const myGlobalFunction: MyGlobalFunctionType;

Then in a regular .ts file, but imported as side-effect, you actually implement it:

global/* or window */.myGlobalFunction = function (name: string) {
  console.log("Hey !", name);
};

And finally use it elsewhere in the codebase, with either:

global/* or window */.myGlobalFunction("Kevin");

myGlobalFunction("Kevin");
🌐
JavaScript in Plain English
javascript.plainenglish.io › how-to-create-global-variables-in-typescript-with-node-js-9ca24f648991
How to Create Global Variables in TypeScript with Node.js | by Anthony Luzquiños | JavaScript in Plain English
February 2, 2023 - Well, it was pretty easy, we just had to extend from NodeJS.Global. Then we had to declare a global variable and like magic, our global variable was available anywhere.
🌐
Marius Schulz
mariusschulz.com › blog › declaring-global-variables-in-typescript
Declaring Global Variables in TypeScript — Marius Schulz
April 16, 2020 - TypeScript will merge this interface definition together with the Window interface defined in lib.dom.d.ts, resulting in a single Window type. Now, the following assignment will no longer produce a type error: ... Note that once again, this approach will not work within a JavaScript module. You'll need to use the declare global { ...