How to declare Global Variables in TypeScript

avatar
Borislav Hadzhiev

Last updated: Feb 28, 2024
4 min

banner

# Declare Global Variables in TypeScript

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.

TypeScript looks for .d.ts file in the same places it looks for your regular .ts files.

In your src directory, create a types directory that contains the following index.d.ts file:

src/types/index.d.ts
/* eslint-disable no-var */ declare global { var country: string; function multiply(a: number, b: number): number; } export {};
The code for this article is available on GitHub

The example shows how to extend the global object with a country property that is a string and a multiply function.

Note that this will be different in your use case, so make sure to adjust the property names and the types.

Make sure to use the var keyword to add typings for properties you intend to set and use in other files.

You need to add the names and types of all of the properties you intend to access on the global object.

# Turning off type checking for specific properties

For example, if you don't know the type of the specific property and want to turn off type checking, set it to any.

src/types/index.d.ts
/* eslint-disable no-var */ declare global { var country: any; // ๐Ÿ‘ˆ๏ธ disables type checking for property function multiply(a: number, b: number): number; } export {};
The code for this article is available on GitHub

Now, I'm able to set and access the specified property on the global object if using Node.js or on the window object if in the browser.

index.ts
global.country = 'Germany'; console.log(global.country); // ๐Ÿ‘‰๏ธ "Germany" // โœ… Can also be accessed directly console.log(country); // ๐Ÿ‘‰๏ธ "Germany" // ๐Ÿ‘‡๏ธ if you are on the browser // console.log(window.country); global.multiply = function (a: number, b: number) { return a * b; }; console.log(global.multiply(16, 30)); // ๐Ÿ‘‰๏ธ 450 // โœ… Can also be accessed directly console.log(multiply(13, 10)); // ๐Ÿ‘‰๏ธ 130 // ๐Ÿ‘‡๏ธ if you are on the browser // console.log(window.multiply(15, 15));

set and access specified property on global object

# Solve ts-node related issues

Note that you might still be getting an error in your terminal if you are using ts-node.

The problem is with ts-node not recognizing local declaration files.

To resolve the issue, use the --files flag with your ts-node command, so instead of ts-node ./src/index.ts you should run ts-node --files ./src/index.ts.

I use nodemon with ts-node and here are the contents of my nodemon.json file.

nodemon.json
{ "watch": ["src"], "ext": ".ts,.js", "ignore": [], "exec": "ts-node --files ./src/index.ts" }
The code for this article is available on GitHub

After adding the --files flag (only required if using ts-node), restart your server and you should be good to go.

# Properties are accessible on the global and window objects

Note that this makes the multiply function and the country property accessible directly (globally) and on the global (Node.js) or window (Browser) objects.

index.ts
global.country = 'Germany'; console.log(country); // ๐Ÿ‘‰๏ธ "Germany" global.multiply = function (a: number, b: number) { return a * b; }; console.log(multiply(13, 10)); // ๐Ÿ‘‰๏ธ 130

properties are accessible on global and window objects

If you try to access a property that you haven't explicitly added to your declare global {} object, you'd get an error:

index.ts
// โ›”๏ธ Error: global.hello = 'bobbyhadz.com';

# Add the path to your types directory to your tsconfig.json

If you still get an error in your IDE, try adding the path to your types directory to your tsconfig.json file.

tsconfig.json
{ "compilerOptions": { // ... rest "typeRoots": ["./node_modules/@types", "./src/types"] } }

We used the export {} line in our index.d.ts file to mark it as an external module. A module is a file that contains at least 1 import or export statement. We are required to do that to be able to augment the global scope.

Note that you will have to change the contents of the provided index.d.ts file according to your use case.

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.

# Using a type assertion

If you can't get this to work, try using a type assertion for a quick and dirty solution.

index.ts
// ๐Ÿ‘‡๏ธ or (global as any) if you are in Node.js (window as any).example = 'bobbyhadz.com'; console.log((window as any).example);

This approach should only be used when nothing else works as it is quite annoying to have to type the window or global object as any every time you need to access a property.

I've also written a detailed guide on how to declare global types in TS.

You might also use a more direct approach when declaring global variables.

# Using a more direct approach to declare global variables

Here is an example that doesn't use the declare global syntax.

src/types/index.d.ts
/* eslint-disable no-var */ /** * IMPORTANT: ๐Ÿ‘‡๏ธ * file should not have imports or exports */ declare var country: string; declare function multiply(a: number, b: number): number;

The file directly declares a country and multiply global variables.

Note that the .d.ts file should not contain any imports or exports, otherwise, you'd have to use the declare global{} syntax from the previous code samples.

Now you can set and access the global variables in your code.

index.ts
global.country = 'Germany'; console.log(country); // ๐Ÿ‘‰๏ธ "Germany" // ๐Ÿ‘‡๏ธ if you are on the browser // console.log(window.country); global.multiply = function (a: number, b: number) { return a * b; }; console.log(multiply(13, 10)); // ๐Ÿ‘‰๏ธ 130

If you need to extend the Window type, check out the following article.

I've also written an article on how to extend Array.prototype in TS.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev