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 - So, avoid code that uses global variables at the root of the files. Or avoid it altogether. :) ... import "express"; declare global { namespace Express { interface Request { token: string, UserID: string } } } export { }; ... This post talks about how to encrypt the user password using Sequelize and store in PostgreSQL. ... A step-by-step guide on setting up your own TCP client/server application with Node.js.
Discussions

Extending TypeScript Global object in node.js - Stack Overflow
This is better, tnx. is there any ... declare global? 2017-12-22T02:03:01.953Z+00:00 ... I get an error "A declare modifier cannot be used in already ambient context" . 2019-02-09T11:20:43.423Z+00:00 ... Putting the following file into our project's root directory worked. ... We're using "@types/node": "^7.0.18" and TypeScript Version 2.3.4. Our tsconfig.json file looks ... More on stackoverflow.com
🌐 stackoverflow.com
Global Variables
You can just export an object from any module. export const global = { foo: "and I call it a day } import { global } from "./global.ts"; global.foo = "Modified by a different file." Sure you might need to add an import statement everywhere, but then you'll be able to see everywhere it's being used as well More on reddit.com
🌐 r/typescript
3
2
February 12, 2024
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
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
June 30, 2014
🌐
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 - In case we want to have a custom location we have to add it to the typeRoots array in our tsconfig.json. Something like: { // ... "compilerOptions": { // ... "typeRoots": ["path/to/our/global/variables.d.ts"] // ... } } In case you are using ts-node to run your project you have to add the files option in your tsconfig.json file, or follow this guide.
🌐
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 - 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 · declare global { var Config: { Foo: string; }; var Foo: string; }export { }; ... Make sure the tsconfig.json has proper sections for include and exclude . Example follows: "include": [ "src/**/*.ts", ], "exclude": [ "node_modules", "<node_internals>/**", "bin/**" ]
🌐
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.
🌐
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?

Find elsewhere
🌐
Bobby Hadz
bobbyhadz.com › blog › typescript-declare-global-variable
How to declare Global Variables in TypeScript | bobbyhadz
TypeScript looks for .d.ts files in the same places it looks for your regular .ts files · The location is determined by the include and exclude settings in your tsconfig.json file. If you can't get this to work, try using a type assertion for a quick and dirty solution. ... Copied!// 👇️ or (global as any) if you are in Node.js (window as any).example = 'bobbyhadz.com'; console.log((window as any).example);
🌐
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.
🌐
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 - In case we want to have a custom location we have to add it to the typeRoots array in our tsconfig.json. Something like: { ... "compilerOptions": { ... "typeRoots": ["path/to/our/global/variables.d.ts"], ... } } In case you are using ts-node to run your project you have to add the files option in your tsconfig.json file, or follow this guide.
🌐
Marcinbiernat
marcinbiernat.pl › 2020 › 03 › nodejs-globals
NodeJS globals and TypeScript · Marcin Biernat
March 22, 2020 - 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:
🌐
Blake Williams
blakewilliams.me › posts › using-ts-node-with-global-types
Using ts-node with Global Types | Blake Williams
September 7, 2020 - Updated: 12/30/21 for recent versions of TypeScript/ts-node · 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:
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");
🌐
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 - The answer is pretty simple and some of you JS veterans might have already guessed it, but still let me explain · First things first, This solution will work if you use var because var has the scope of current execution context and here the variable is declared out side of any function so it means variable is declared at the global scope and global variables in JS are attached to global object which in a browser environment is aliased to the window object.
🌐
JSDev
jsdev.space › howto › global-vars-ts
How to Use Global Variables in TypeScript Safely - JsDev Space
This article provides a detailed, ... undocumented set of magic values. In JavaScript, a global variable is any value attached to the global execution context, such as: window in browsers · global in Node.js ·...
🌐
Stack Abuse
stackabuse.com › using-global-variables-in-node-js
Using Global Variables in Node.js
July 8, 2024 - Now that we have a better understanding of what a global variable in Node is, let's talk about how we actually set up and use a global variable. To set up a global variable, we need to create it on the global object. The global object is what gives us the scope of the entire project, rather ...