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

Answer from edvard chen on Stack Overflow
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");
🌐
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.
Discussions

typescript - Call a global variable inside module - Stack Overflow
Find centralized, trusted content ... you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I have a typescript file called Projects.ts that I want to reference a global variable declared in ... More on stackoverflow.com
🌐 stackoverflow.com
How to define a global variable in a typescript module, which could be used in other modules directly without import?
Currently, we have two ways to ... declare global in a module. But the first one method need to publish to @types, which is just for modules written in javascript, and the second one need to import to use it. Is there any way to define a variable in a typescript module which ... More on github.com
🌐 github.com
5
September 4, 2017
How to create a truly global variable in TypeScript without window? - LambdaTest Community
How can I create a global variable in TypeScript? In JavaScript, I can define a variable globally and access it across files. For example: something = 'testing'; And then use it in another file: if (something === 'testing') In TypeScript, I tried using the window object, like this: In a .d.ts ... More on community.lambdatest.com
🌐 community.lambdatest.com
0
September 24, 2024
Is it possible to declare a global function/variable type that can be made available in all files part of compilation?
I found a solution. Not very advised to follow this. But this is a solution that works: create a global.d.ts file in say a folder named, say types, in your src declare the global function or variable append this local types folder to typeRoots key in tsconfig compiler options That makes the declaration available globally This is the post that lead me to the answer. Key takeaways from that post: When we either import/export from a .d.ts file, then it becomes a module. When it becomes a module, we have to explicitly import the required utils The isolatedModules flag can't be turned off in CRA. Therefore we can only use .d.ts extension files to export global types. Global types are ill advised! I'm using it for a logger only. Hopefully won't have any probs. More on reddit.com
🌐 r/typescript
5
5
January 28, 2021
🌐
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 › by-example.html
TypeScript: Documentation - Declaration Reference
The global variable foo contains the number of widgets present. ... Use declare var to declare variables. If the variable is read-only, you can use declare const. You can also use declare let if the variable is block-scoped. ... You can call the function greet with a string to show a greeting ...
🌐
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.
🌐
Marius Schulz
mariusschulz.com › blog › declaring-global-variables-in-typescript
Declaring Global Variables in TypeScript — Marius Schulz
April 16, 2020 - Every now and then, you might want to statically type a global variable in TypeScript. For example, in some of my web applications, I need to pass a few properties from my markup rendered on the server to my JavaScript code running in the browser. To do that, I typically define a global variable named __INITIAL_DATA__ within an inline script and assign to it a JSON-serialized object: <script> window.__INITIAL_DATA__ = { userID: "536891193569405430", }; </script>
🌐
GeeksforGeeks
geeksforgeeks.org › typescript › how-to-create-a-global-variable-in-typescript
How to Create a Global Variable in TypeScript ? - GeeksforGeeks
April 28, 2025 - Example: In this example, we are using var, let, and const to create a global variable in TypeScript. ... var globalVar: string = "I am a global variable using var"; let globalLet: string = "I am a global variable using let"; const globalConst: number = 42; function useGlobalVarLetAndConst() { console.log(globalLet, globalConst, globalVar); } useGlobalVarLetAndConst(); // Accessible here
Find elsewhere
🌐
JSDev
jsdev.space › howto › global-vars-ts
How to Use Global Variables in TypeScript Safely
Always use explicit assignment to window/globalThis. Declarations and runtime values belong in different files. Overuse leads to unpredictable dependencies. Prefer modules or environment variables. Global variables in TypeScript are safe and maintainable when declared properly.
🌐
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 - Using Webpack’s define plugin to define global variables in your code based on build type or even if you are using any other bundler to do something similar. Using a 3rd party library of script over CDN which uses window object and add its functions or variables to window object. E.g. (Intercom) Or If you are using some variables which are being attached to windows for some reason. At smallcase, we are currently in the process of migrating our codebases to typescript for better compile time type safety.
🌐
EDUCBA
educba.com › home › software development › software development tutorials › typescript tutorial › typescript global variable
TypeScript Global Variable | Quick Glance on TypeScript Global Variable
June 12, 2023 - In TypeScript, there is no keyword for declaring global variables, such as the “global” keyword in other programming languages. Sometimes in TypeScript, they use the keyword “declare” to declare variables such as “declare var” for ...
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Webtips
webtips.dev › solutions › declare-global-variables-in-typescript
3+1 Ways to Declare Global Variables in TypeScript - Webtips
September 20, 2022 - To declare global variables in TypeScript, create a type definition file ending with .d.ts, and use the declare var syntax to declare global variables.
🌐
Tim Mousk
timmousk.com › blog › typescript-global-variable
How To Create A Global Variable In TypeScript? – Tim Mouskhelichvili
January 10, 2023 - typescriptdeclare global { var __GLOBAL_VAR__: { name: string; }; } export {}; You can now use this variable anywhere in your TypeScript code.
🌐
YouTube
youtube.com › typewithme
Declaring Global Variables in TypeScript - YouTube
Declaring global variables in typescript is something that you now and then need to do. But how do you do it so that the compiler of typescript is happy, how...
Published   April 19, 2020
Views   1K
🌐
GitHub
github.com › Microsoft › TypeScript › issues › 18237
How to define a global variable in a typescript module, which could be used in other modules directly without import? · Issue #18237 · microsoft/TypeScript
September 4, 2017 - Currently, we have two ways to define a global variable, the first one is use @types define it, and the second one is use declare global in a module. But the first one method need to publish to @types, which is just for modules written in ...
Author   acrazing
🌐
Virtual Curiosities
virtualcuriosities.com › articles › 3112 › how-to-declare-global-variables-in-typescript
How to Declare Global Variables in Typescript - Virtual Curiosities
November 24, 2024 - If you don't define the global variable yourself but it comes from a third-party library (e.g. JQuery), or you conditionally define it using window, you can declare that it will exist using the declare keyword. Like var, this only works if you don't have any export or import statements. Unlike var, this doesn't generate Javascript code, as it's a declaration purely for Typescript use.
🌐
Tektutorialshub
tektutorialshub.com › home › typescript › variable scope in typescript : global, local & function
Variable Scope in TypeScript : Global, Local & function - Tektutorialshub
March 15, 2023 - The Typescript variables have three scopes. Global, Function and local. Using var you can create global & function variable. While We use let & const to all the three.
🌐
Plain English
plainenglish.io › blog › typescript-and-global-variables-in-node-js-59c4bf40cb31
TypeScript and Global Variables in Node.js
August 14, 2021 - index.ts initializes the global logger and then begins to use it. Note that *initializing *the variable requires the use of global. (or globalThis. ), but using it doesn't.
🌐
LambdaTest Community
community.lambdatest.com › general discussions
How to create a truly global variable in TypeScript without window? - LambdaTest Community
September 24, 2024 - How can I create a global variable in TypeScript? In JavaScript, I can define a variable globally and access it across files. For example: something = 'testing'; And then use it in another file: if (something === 'tes…
🌐
Medium
medium.com › design-bootcamp › understanding-types-globals-interfaces-constants-and-props-in-typescript-b91490a024a8
Understanding Types, Globals, Interfaces, Constants, and Props in TypeScript | by Israel | Bootcamp | Medium
August 31, 2023 - In TypeScript, the declare keyword is used to indicate that a variable is declared elsewhere, typically outside the current TypeScript project. This is useful when you want to reference variables or libraries that are provided by external sources, ...