233

In JavaScript I can just do this:

 something = 'testing';

And then in another file:

 if (something === 'testing')

and it will have something be defined (as long as they were called in the correct order).

I can't seem to figure out how to do that in TypeScript.

This is what I have tried.

In a .d.ts file:

interface Window { something: string; }

Then in my main.ts file:

 window.something = 'testing';

then in another file:

 if (window.something  === 'testing')

And this works. But I want to be able to lose the window. part of it and just have my something be global. Is there a way to do that in TypeScript?

(In case someone is interested, I am really trying to setup my logging for my application. I want to be able to call log.Debug from any file without having to import and create objects.)

4
  • 4
    Alternatively: Don't create globals. Importing is really easy with vscode. Just type the thing you want to use, hit tab to auto-import, and continue on. Commented Dec 30, 2020 at 5:04
  • 3
    @DevinRhode Ideally that's the way to go. But sometimes you need to use a JavaScript library that declares global variables and want to use a typed version of it in your project. Commented Aug 5, 2023 at 22:50
  • It's true, actually I had a use for globals recently, and created a new approach, see: stackoverflow.com/a/76844373/565877 Commented Aug 7, 2023 at 16:49
  • Typescript global declarations are more subtle than you might think. For a better understanding, I recommend these answers, one from here, one from a different question: Create a global variable in TypeScript Using globalThis in Typescript Commented Nov 16, 2023 at 22:16

20 Answers 20

175

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

Sign up to request clarification or add additional context in comments.

16 Comments

But how would you do this without the 'var' hack? I guess that means, how would I do type augmentation on globalThis?
@Tom var is necessary. But you can just declare variable without initialization
Worked for me (at least for now) thanks so much, I wish this answer would move up. FYI: In my case I needed to add // @ts-ignore above the globalThis line for the linter.
@edvardchen, I could finally solve the issue, it was related to ts-node, this is a related question to that, I have also wrote a Medium article about it, here is it.
@gwhiz only a declaration. You should always use globalThis to do the actual assignment. var age = 123 won't work.
|
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");

9 Comments

( Just making a passing comment ) Talk about a lot of work to create a simple global variable! lol
@Benoit I don't get the part that says "but imported as side-effect". What do you mean by that?. I tried doing this, but it's not working for me, could you share a source code example?
It means import it somewhere so that the code gets executed, so myGlobalFunction becomes available. Like in it's own <script> tag at the top of your page. Now other scripts that load later can use it. It's a "side effect" because it changes things for the other scripts (by providing myGlobalFunction).
This works fine for .ts files but when I use window.myGlobalFunction in my .tsx files, it doesn't. What else do I need to change?!
Where do you put the d.ts file, and how do you configure TypeScript to load it?
This is ridiculously complicated.
|
39

This is how I have fixed it:

Steps:

  1. Declared a global namespace, for e.g. custom.d.ts as below :
declare global {
    namespace NodeJS {
        interface Global {
            Config: {}
        }
    }
}
export default global;
  1. Map the above created a file into "tsconfig.json" as below:
"typeRoots": ["src/types/custom.d.ts" ]
  1. Get the above created global variable in any of the files as below:
console.log(global.config)

Note:

  1. typescript version: "3.0.1".

  2. In my case, the requirement was to set the global variable before boots up the application and the variable should access throughout the dependent objects so that we can get the required config properties.

1 Comment

Since Node 16 use declare global { var whatever: type }
26

The text posted here is a short version of the article TypeScript and Global Variables in Node.js

Since the release of TypeScript 3.4 there's a documented way to do it.

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
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/**"
  ]

To use the variables, just do something like:

import * as Logger from './logger';

// Initialize early
global.log = Logger;

// Use it
log.Info("Booting system...");

1 Comment

Finally.. export { }; was the key. In .ts you can use global.log or globalThis.log interchangeably.
20

I found a way that works if I use JavaScript combined with TypeScript.

logging.d.ts:

declare var log: log4javascript.Logger;

log-declaration.js:

log = null;

initalize-app.ts

import './log-declaration.js';

// Call stuff to actually setup log.  
// Similar to this:
log = functionToSetupLog();

This puts it in the global scope and TypeScript knows about it. So I can use it in all my files.

NOTE: I think this only works because I have the allowJs TypeScript option set to true.

1 Comment

In your initalize-app.ts file you can use: declare var log: any; Then you don't need to have the d.ts file or the js file. You could replace any with an actual type or an interface definition as well.
7

In my case I'm trying to define global "log" variable so the steps were:

  1. configure your tsconfig.json to include your defined types (src/types folder, node_modules - is up to you):

    ...other stuff...
    "paths": {
      "*": ["node_modules/*", "src/types/*"]
    }
    
  2. create file src/types/global.d.ts with following content (no imports! - this is important), feel free to change any to match your needs + use window interface instead of NodeJS if you are working with browser:

    /**
     * IMPORTANT - do not use imports in this file!
     * It will break global definition.
     */
    declare namespace NodeJS {
        export interface Global {
            log: any;
        }
    }
    
    declare var log: any;
    
  3. Now you can finally use/implement log where its needed:

    // in one file
    global.log = someCoolLogger();
    // in another file
    log.info('hello world');
    // or if its a variable
    global.log = 'INFO'
    

4 Comments

What's the paths in tsconfig.json? The docs don't have any mention of it.
And why is Global capitalized in the definitions, but not in actual usage?
@tambre not sure why TS docs don't have it documented, you can find some details regarding this config here: json.schemastore.org/tsconfig and here: basarat.gitbooks.io/typescript/docs/project/tsconfig.html Regarding Global with capital - this is how "global" interface declaration named in nodejs namespace.
paths is not working for me. I have to add this: "files": [ "./src/types/global.d.ts"], I don't understand why this file isn't added with my include: "include": [ "src/types/**/*.d.ts", "src/**/*", ], Without adding the specific file to files, it doesn't work for me
5

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.

Simplest case with global scope

declare var ENVIRONMENT: string;
globalThis.ENVIRONMENT = 'PROD';
console.log(ENVIRONMENT);
console.log(globalThis.ENVIRONMENT);
// output
// PROD
// PROD

This file doesn't import or export so it's a global scope file. You can compile the above TypeScript code without any error. Note that you have to use var. Using let will throw error TS2339: Property 'ENVIRONMENT' does not exist on type 'typeof globalThis'.

You might notice that we declared the variable as opposed to the following which also works.

var ENVIRONMENT: string;
ENVIRONMENT = 'DEV';
globalThis.ENVIRONMENT = 'PROD';
console.log(ENVIRONMENT);
console.log(globalThis.ENVIRONMENT);
// output
// DEV
// PROD

The output is from Nodejs v12.14.1. I also tested it in Chrome (after compiling to JS) and both output PROD. So I'd suggest using globalThis all the time.

Simple case with module scope

declare var ENVIRONMENT: string;
globalThis.ENVIRONMENT = 'PROD';
export {};

Once we add export statement, it becomes a module scope file, which throws error TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature. The solution is to augment global scope.

declare global {
  var ENVIRONMENT: string;
}
globalThis.ENVIRONMENT = 'PROD';
console.log(globalThis.ENVIRONMENT);
export {};

You still have to use var, otherwise you will get error TS2339: Property 'ENVIRONMENT' does not exist on type 'typeof globalThis'..

Import for side effect

// ./main.ts
import './environment_prod';

console.log(ENVIRONMENT);
console.log(globalThis.ENVIRONMENT);
// ./environment_prod.ts
declare var ENVIRONMENT: string;
globalThis.ENVIRONMENT = 'PROD';

Or

// ./environment_prod.ts
declare global {
  var ENVIRONMENT: string;
}
globalThis.ENVIRONMENT = 'PROD';
export {}; // Makes the current file a module.

Browserify two files

Suppose both main.ts and environment_prod.ts are entry files. Browserify will wrap them (after compiled to JS) into local scoped functions which necessitates the use of globalThis.

// ./main.ts
declare var ENVIRONMENT: string;
console.log(ENVIRONMENT);
console.log(globalThis.ENVIRONMENT);

// ./environment_prod.ts
declare var ENVIRONMENT: string;
globalThis.ENVIRONMENT = 'PROD';

But it's more type-safe to share a declaration file which can then be imported by both entry files, to avoid typos of variable names or type names.

// ./main.ts
import './environment';

console.log(ENVIRONMENT);
console.log(globalThis.ENVIRONMENT);

// ./environment_prod.ts
import './environment';

globalThis.ENVIRONMENT = 'PROD';

// ./environment.ts
type Environment = 'PROD' | 'DEV' | 'LOCAL';

declare var ENVIRONMENT: Environment;

Note that the order matters: browserify environment_prod.js main.js > bin.js

Comments

5

It works on browser.
I found this in https://stackoverflow.com/a/12709880/15859431

declare global {
    interface Window {
        myGlobalFunction: myGlobalFunction
    }
}

Comments

5

I'm using only this:

import {globalVar} from "./globals";
declare let window:any;
window.globalVar = globalVar;

3 Comments

This throws away all type information. May as well use Javascript.
This solution makes sense when you are making frontend completely outside from backend (for different purposes), like different teams or due to security reasons. And then backend inject something inside window. I honestly prefer specify EACH variable inside components in this case. So I believer this solution might have a life :) Do not think this is wide case, but I faced with it one day....
To extend window in a typesafe way: declare global { interface Window { myInjectedVar: string; } }
3

Okay, so this is probably even uglier that what you did, but anyway...

but I do the same so...

What you can do to do it in pure TypeScript, is to use the eval function like so :

declare var something: string;
eval("something = 'testing';")

And later you'll be able to do

if (something === 'testing')

This is nothing more than a hack to force executing the instruction without TypeScript refusing to compile, and we declare var for TypeScript to compile the rest of the code.

7 Comments

@DragonRock I tried Chrome and FF. So I'm really not sure what was going on. Anyway ended up doing declare var myglobalvar; (<any>window).myglobalvar= {}; Then I can reference it without window afterwards.
This really should be done with a .d.ts definition file instead.
This works for me: export declare const SERVER = "10.1.1.26";
Using eval is highly discouraged that's why I suggest using this solution stackoverflow.com/a/56984504/5506278
Using eval is dirty, consider using Object.assign(globalThis, {something: 'something'}) instead
|
3

I needed to make lodash global to use an existing .js file that I could not change, only require.

I found that this worked:

import * as lodash from 'lodash';

(global as any)._ = lodash;

Comments

3

Also check out the answer here

// global.d.ts
export const thisIsAModule = true; // <-- definitely in a module

declare global {
    var foo: string;
}

Comments

2

This is working for me, as described in this thread:

declare let something: string;
something = 'foo';

Comments

1

If anyone uses Deno:

// global.ts
interface Global {
    some_number: number;
}

export const global = {
    some_number: 1,
} as Global;

Then every script that imports global can modify its values (but not global itself!) like this:

// test.ts
import { global } from "./global.ts";
export function test() {
    global.someNumber++;
}

You can prove that it works by running the function from another file:

// main.ts
import { global } from "./global.ts";
import { test } from "./test.ts";

console.log(global);
test();
console.log(global);

… will print:

{ someNumber: 1 }
{ someNumber: 2 }

1 Comment

This is better than most answers. You avoided creating .d.ts, and avoided touching tsconfig.json! But there's a funny thing in the code here: If we are already importing ane exporting, we can drop interface Global { ... } and } as Global; - just have a shared mutable global Object that you import/export and mutate as needed. If people can do this, given their constraints, it's definitely better than other approaches.
1

Create class and define static constants there.

export class Settings {
  static something: 'someone';
  static apiUrl = '/api';
  static defaultPageSize = 5;
}

Can be used anywhere in the application.

url = Settings.apiUrl;

Confirmed to work with TS ver 5.5. Type safety. No javascript hackery needed.

Comments

1

I owe some credit to @Yuxuan Xie.

This is my current strategy:

Preconditions:

Let's evaluate the best strategy for you.

  1. If you can have a shared mutable "global" object that you control, and simply import/export where you need it, that's better than mucking around with globalThis or declare global etc.
  2. If you can "wrap" some other value with typescript, that's also great.
  • export const Object_keys_typed = Object.keys as SOME_TYPE

Lastly

If there's just some global being created outside of your typescript code, proceed.

Define the globals

  1. Create this file:
  2. define-globals-for-some-specific-thing.ts Add add your code like this:
// Importing constants is fine:
// import type { FOO } from './constants';

// Import this in order to access these globals.
declare global {

  // Because this is a `const/let`, typescript will complain if you access it via `globalThis.WAS_LOADED_VIA_INDEX_HTML`,
  // You instead need to remove the `globalThis.` prefix
  /** determine if this was loaded via index.html, or some other npm/script tag function */
  const WAS_LOADED_VIA_INDEX_HTML: boolean | undefined;

  // This can be accessed via `window/globalThis.CanBeReadOffWindow`
  var CanBeReadOffWindow: 'asdf' | undefined;
}

// Makes the current file a module, with a clear importable name
export const defineGlobals = undefined;

Use the globals:

Inside myFile.ts:

import './define-globals-for-specific-task.ts';

export const wasLoadedViaIndexHtml = () => {
  return WAS_LOADED_VIA_INDEX_HTML;
};

Why this is good

  1. We avoid touching tsconfig.json.
  2. We avoid creating .d.ts files.
  3. We're forced to use imports/exports where we want to access the globals.
  • This means if you scan import statements to get the "gist" of a file, you can see it will interact with some globals defined in define-globals-for-specific-task.
  • We can search for these import statements, and find everywhere we use a global

There's probably a better name template than define-globals-for-specific-task - perhaps define-SPECIFIC_TASK-global-types

Comments

1

This is how you create global variables for node app and TypeScript

File name is called typings/index.ts:

declare global {
  var countSkipped: number;
  var countProcessed: number;
  var countLibUsedByFile: Record<string, number>;
}

export {};

If you happen to overrides a few prototypes, here's how you can add the typescript definition for the string prototype:

declare global {
  interface String {
    blue(): string;
    yellow(): string;
    green(): string;
    red(): string;
  }
}

export {};

This is the sample prototype for the above string:

String.prototype.blue = function () {
  return `\x1b[36m${this}\x1b[0m`;
};

String.prototype.yellow = function () {
  return `\x1b[33m${this}\x1b[0m`;
};

String.prototype.green = function () {
  return `\x1b[32m${this}\x1b[0m`;
};

String.prototype.red = function () {
  return `\x1b[31m${this}\x1b[0m`;
};

Comments

0

As an addon to Dima V's answer this is what I did to make this work for me.

// First declare the window global outside the class

declare let window: any;

// Inside the required class method

let globVarName = window.globVarName;

2 Comments

Can the person who down-voted this explain the reason?
Well, this is a solution like putting a piece of black tape over your "check engine" light on your dashboard. It fixes the problem but not in the right way. It obliterates types. It's not an optimal solution; it's a workaround that also works around the main purpose of typescript: to have types.
-1

I'm using this:

interface Window {
    globalthing: any;
}

declare var globalthing: any;

Comments

-1

First declare your Global variable Like this:

declare global {
  var options: {
    billingAddress: {
      country: string;
      state: string;
      city: string;
      postcode: string;
      street1: string;
      street2: string;
    };
    mandatoryBillingFields: {
      country: boolean;
      state: boolean;
      city: boolean;
      postcode: boolean;
      street1: boolean;
      street2: boolean;
    };
  };
}

In functions you can use Like this:

const updateGlobalVariable = () => {
      window.options = {
        billingAddress: {
          country: 'US',
          state: 'NY',
          city: 'New York',
          postcode: '12345',
          street1: 'Suite 1234',
          street2: 'Some Road',
        },
        mandatoryBillingFields: {
          country: true,
          state: true,
          city: true,
          postcode: true,
          street1: true,
          street2: false,
        },
      };
    };

1 Comment

I was specifically asking for a way to remove the window. part of the referencing of the variable. (To reference it directly). This still uses window. to get at the variable. window is global here, not options.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.