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
Many libraries simply expose one or more global variables for use. For example, if you were using jQuery, the $ variable can be used by simply referring to it: ... You’ll usually see guidance in the documentation of a global library of how to use the library in an HTML script tag:
Discussions

Typescript global variables - Stack Overflow
Is there a convenient way to have global variables accessible within modules,without compiler errors, ie CANVAS_WIDTH used below? export class Bullet { x: number = 22; y: numb... More on stackoverflow.com
🌐 stackoverflow.com
September 10, 2015
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 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 @ty... 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
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
🌐
Reddit
reddit.com › r/typescript › [question] best way to declare classes and global variables
r/typescript on Reddit: [Question] Best way to declare classes and global variables
October 1, 2018 -

Hello folks,

first of all my apologies for my language barriers.

As a main JAVA programmer I've started to split my classes in different TS files like in JAVA. But as I get several messages of 'Cannot find name X' Ive becoming doubtful of my modus operandi.

Also Im getting similar troubles declaring global variables in the different files... again the 'Cannot find name X'.

It seems more complex that it should be... :/

How is it supposed to be built?

Top answer
1 of 5
4
  • Global variables: You can't define globals in JAVA, so why try it in Typescript? Do what you would do in Java: Declare a static variable on a class.

  • One class per file: That's perfectly fine and I do it all the time. You have to explicitly import files though. I usually have 1 class per file, and an index.ts that exports all these things. EG:

// core/user/IUserService.ts
import { IUser } from "./IUser"

export interface IUserService {
  getUserById(id: string): Promise<IUser>
}

// core/user/IUser.ts
export interface IUser {
  id: string;
}

// core/user/index.ts
export * from "./IUserService"
export * from "./IUser"

// core/index.ts
export * from "./user"

// http/HttpUserService.ts
import { IUserService, IUser } from "../core/user";

export class HttpUserService implements IUserService {
  constructor(
    private endpoint: string,
    private fetch: Fetch,
  ) {
  }

  async public getUserById(id: string): Promise<IUser|null> {
    const response = await this.fetch(this.endpoint + "/users/" + id);
    return response.status === 200 ? parseUserResponse(await response.json()) : null;
  }
}

// essentially a prive function
// no need to embed it in the class since it won't be using `this` either
function parseUserResponse(data: any): IUser {
  return ...;
}

// http/index.ts
export * from "./HttpUserService";

// index.ts
export * from "core";
export * from "http";

Also, an example of a "global" variable by using a singleton pattern: https://github.com/tobyhinloopen/injector/blob/master/src/core/Injector.ts

export class Injector {
  public static readonly instance = new Injector();
  ...
}
2 of 5
4

In Java everything defined in the same package shares the same scope; so you can reference a class in another file without explicitly importing it. Typescript is different: every file has its own scope; so you must explicitly export and import classes and variables between files.

A file in a Typescript project is called a "module" because it gets its own scope. Javascript works the same way when working with CommonJS or ES modules.

CommonJS is the Node module system - Typescript is typically configured to use this system. A bundler (either tsc, Webpack, or Parcel) combines CommonJS modules into one file for use in a browser.

ES modules are the new ECMAScript standard module system. Browsers are upgrading to be able to consume ES modules natively, which may make bundling unnecessary in some cases. But it will take some time for the community to adjust to this new module system. The old module-less system where all browser scripts share one global namespace has been on the way out for some time.

🌐
TypeScript
typescriptlang.org › docs › handbook › declaration-files › by-example.html
TypeScript: Documentation - Declaration Reference
December 29, 2025 - Classes can have properties and methods as well as a constructor. ... 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.
🌐
TutorialsPoint
tutorialspoint.com › typescript › typescript_variables.htm
TypeScript - Variables
Static fields can be accessed using the class name. Local Scope − Local variables, as the name suggests, are declared within the constructs like methods, loops etc. Local variables are accessible only within the construct where they are declared. The following example illustrates variable scopes in TypeScript. var global_num = 12 //global variable class Numbers { num_val = 13; //class variable static sval = 10; //static field storeNum():void { var local_num = 14; //local variable } } console.log("Global num: "+global_num) console.log(Numbers.sval) //static variable var obj = new Numbers(); console.log("Global num: "+obj.num_val)
🌐
Marius Schulz
mariusschulz.com › blog › declaring-global-variables-in-typescript
Declaring Global Variables in TypeScript — Marius Schulz
April 16, 2020 - In that file, you can declare all global variables you'll use: ... As long as globals.d.ts is part of your TypeScript project, the compiler will know that __INITIAL_DATA__ is a global variable, and it will let you access it via both __INITIAL_DATA__ as well as window.__INITIAL_DATA__.
🌐
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.
Top answer
1 of 3
31

You need to define those properties as static, then you can access it easily like this,

export class Game {
    static canvas: JQuery;
    static CANVAS_WIDTH: number;
    static CANVAS_HEIGHT: number;
    bullet: Bullet;

    constructor(canvasElem: JQuery) {
        Game.canvas = canvasElem;
        Game.CANVAS_WIDTH = Game.canvas.width();
        Game.CANVAS_HEIGHT = Game.canvas.height();
    }
}

export class Bullet {
    x: number = 22;
    y: number = 22;

    public inBounds() {
        // accessing static properties
        return this.x >= 0 && this.x <= Game.CANVAS_WIDTH && this.y >= 0 && this.y <= Game.CANVAS_HEIGHT;
    }
}

This compiles to:

define(["require", "exports"], function(require, exports) {
    var Game = (function () {
        function Game(canvasElem) {
            Game.canvas = canvasElem;
            Game.CANVAS_WIDTH = Game.canvas.width();
            Game.CANVAS_HEIGHT = Game.canvas.height();
        }
        return Game;
    })();
    exports.Game = Game;

    var Bullet = (function () {
        function Bullet() {
            this.x = 22;
            this.y = 22;
        }
        Bullet.prototype.inBounds = function () {
            // accessing static properties
            return this.x >= 0 && this.x <= Game.CANVAS_WIDTH && this.y >= 0 && this.y <= Game.CANVAS_HEIGHT;
        };
        return Bullet;
    })();
    exports.Bullet = Bullet;
});
//# sourceMappingURL=dhdh.js.map
2 of 3
3

This is a contrived example, but rather than trying to push to global scope, you can use the module scope to enclose a variable that will be used from several classes.

module MyModule {
    var x: number = 5;

    export class FirstClass {
        doSomething() {
            x = 10;
        }
    }

    export class SecondClass {
        showSomething() {
            alert(x.toString());
        }
    }
}

var a = new MyModule.FirstClass();
a.doSomething();

var b = new MyModule.SecondClass();
b.showSomething();

All the usual rules about multiple things using the same variable apply here - you don't want to enforce a particular order of events on the calling code.


Compiles to:

var MyModule;
(function (MyModule) {
    var x = 5;

    var FirstClass = (function () {
        function FirstClass() {
        }
        FirstClass.prototype.doSomething = function () {
            x = 10;
        };
        return FirstClass;
    })();
    MyModule.FirstClass = FirstClass;

    var SecondClass = (function () {
        function SecondClass() {
        }
        SecondClass.prototype.showSomething = function () {
            alert(x.toString());
        };
        return SecondClass;
    })();
    MyModule.SecondClass = SecondClass;
})(MyModule || (MyModule = {}));

var a = new MyModule.FirstClass();
a.doSomething();

var b = new MyModule.SecondClass();
b.showSomething();
Find elsewhere
🌐
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 has three Variable Scope or visibility. They are a local variable, function (class variable) and global variable (global scope)
🌐
JSDev
jsdev.space › howto › global-vars-ts
How to Use Global Variables in TypeScript Safely
The most reliable way to introduce a global variable is to declare it in a .d.ts file. This file should not contain executable code. Its purpose is to tell TypeScript: “this value exists at runtime; here is its type.”
🌐
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 - Hence, global variables are variables defined as a globally available variable and accessible to every part of the program that includes any block of code or functions or class, and such variables are defined in the global scope of the variable.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
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.
🌐
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.
🌐
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 @ty...
Author   acrazing
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › variables-in-typescript
Variables in TypeScript - GeeksforGeeks
June 9, 2025 - globalVar is a global variable, accessible throughout the program. classVar is a private class-level variable, accessible only within the Geeks class. localVar is a local variable, accessible only within the assignNum method.
🌐
w3tutorials
w3tutorials.net › blog › create-a-global-variable-in-typescript
How to Create a Global Variable in TypeScript Without Using 'window.' — w3tutorials.net
True global: No imports required—variables are accessible everywhere. Encapsulated: Variables live in a namespace (e.g., AppGlobals), reducing naming conflicts. Requires a declaration file (*.d.ts). Risk of namespace pollution if overused. A singleton class ensures only one instance exists, making it ideal for managing global state with controlled access (e.g., getters/setters).
🌐
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 === 'testing') In TypeScript, I tried using the window object, like this: In a .d.ts file: interface Window { something: string; } In main.ts: window.something = 'testing'; And in another file: if (window.something === 'testing') This works, but I want to avoid using window. and h...
🌐
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?

🌐
Webdevtutor
webdevtutor.net › blog › typescript-type-global-variable
Mastering TypeScript Types for Global Variables
Before diving into the specifics of declaring global variables, let's quickly define what they are. In TypeScript, a global variable is a variable that is accessible from anywhere within your application.