Recently, I was working on a large TypeScript project where I needed to share data across multiple files without having to pass it through numerous function parameters.
The solution was to use global variables in TypeScript. While global variables are sometimes considered bad practice, there are legitimate use cases where they can significantly simplify your code.
In this article, I will cover everything you need to know about TypeScript global variables, including different methods to declare them, best practices, and potential pitfalls. So let’s dive in!
What are Global Variables in TypeScript?
Global variables in TypeScript are variables that can be accessed from any part of your application. Unlike local variables that are scoped to specific functions or blocks, global variables maintain their values throughout the entire runtime of your program.
Check out: Convert JSON to TypeScript Interface
TypeScript Global Variables: Different Methods
The simplest way to create global variables in TypeScript is to add them to the Window object. This works in browser environments where the Window object is available.
// Extending the Window interface
declare global {
interface Window {
apiKey: string;
userStatus: 'active' | 'inactive';
}
}
// Assigning values to your global variables
window.apiKey = 'YOUR_API_KEY_HERE';
window.userStatus = 'active';
// Using the global variables in another file
console.log(window.apiKey); // Outputs: YOUR_API_KEY_HEREThis method is straightforward, but it has a limitation: it only works in browser environments. If you’re building a Node.js application, this approach won’t work.
Method 2: Using Namespace Global Variables
For TypeScript applications that might run in both browser and Node.js environments, you can use namespaces to declare global variables:
// In a file like globals.ts
namespace AppGlobals {
export let currentUser: string = '';
export let isAuthenticated: boolean = false;
export let sessionTimeout: number = 3600;
}
// In another file
AppGlobals.currentUser = 'John Doe';
console.log(AppGlobals.currentUser); // Outputs: John DoeOutput:

Using namespaces helps organize your global variables and reduces the chance of naming conflicts. It’s like having a dedicated container for your global state.
Check out: Set Default Values for TypeScript Types
Method 3: Using a Global Module
Another approach is to create a module with global declarations:
// In a global.d.ts file
declare global {
var DATABASE_URL: string;
var MAX_CONNECTIONS: number;
}
// In your main file
global.DATABASE_URL = 'mongodb://localhost:27017/myapp';
global.MAX_CONNECTIONS = 100;
// In any other file
console.log(global.DATABASE_URL); // Outputs: mongodb://localhost:27017/myappThis method works in Node.js environments and is particularly useful for configuration variables that shouldn’t change during runtime.
Method 4: Using the globalThis Keyword
The globalThis keyword provides a standard way to access global variables across different JavaScript environments:
export {}; // Ensures this file is treated as a module
declare global {
var COMPANY_NAME: string;
var TAX_RATE: number;
}
// Assigning global variables
globalThis.COMPANY_NAME = 'Acme Corp';
globalThis.TAX_RATE = 0.07;
// Function using global variables
function calculateTax(amount: number): number {
return amount * globalThis.TAX_RATE;
}
// Output
console.log(`${globalThis.COMPANY_NAME} charges ${calculateTax(100)} in tax on $100`);Output:

The advantage of globalThis approach is that it works across different environments (browsers, Node.js, Web Workers) without requiring conditional code.
Check out: Check the Type of a Variable in TypeScript
Method 5: Using a Singleton Pattern
For more complex global state management, consider using the Singleton pattern:
// In a file like AppState.ts
export class AppState {
private static instance: AppState;
public userPreferences: {
theme: 'light' | 'dark';
fontSize: number;
notifications: boolean;
};
private constructor() {
// Default values
this.userPreferences = {
theme: 'light',
fontSize: 14,
notifications: true
};
}
public static getInstance(): AppState {
if (!AppState.instance) {
AppState.instance = new AppState();
}
return AppState.instance;
}
}
// In another file
import { AppState } from './AppState';
const state = AppState.getInstance();
state.userPreferences.theme = 'dark';
// In yet another file
import { AppState } from './AppState';
console.log(AppState.getInstance().userPreferences.theme); // Outputs: darkOutput:

This pattern is beneficial for managing complex application state that needs to be accessed from multiple components.
Check out: Check If a Variable is Undefined in TypeScript
Best Practices for Using Global Variables
While global variables can be convenient, they can also lead to maintenance issues if not used carefully. Here are some best practices I’ve learned:
- Use TypeScript’s type system: Always declare types for your global variables to prevent type errors.
- Minimize mutability: When possible, use const or readonly to avoid accidental changes to global variables.
- Document your globals: Add comments that explain the purpose of each worldwide variable and indicate who should modify it.
- Consider alternatives: For complex state management, consider using libraries like Redux or MobX instead of raw global variables.
- Namespace your globals: Group related globals together to avoid polluting the global namespace.
- Be careful with initialization order: Ensure global variables are initialized before they’re used.
Here’s an example that follows these best practices:
// In a globals.ts file
namespace Config {
// Application settings that should never change after initialization
export const SETTINGS = {
API_BASE_URL: 'https://api.example.com/v2/',
MAX_UPLOAD_SIZE: 10 * 1024 * 1024, // 10MB in bytes
DEFAULT_TIMEOUT: 30000, // 30 seconds
} as const; // Using 'as const' makes all properties readonly
// Current application state that may change during runtime
export const STATE = {
isLoggedIn: false,
currentPage: 'home',
lastActivity: Date.now()
};
}
// Export for easy importing in other files
export default Config;Conclusion
In this tutorial, we have learned about global variables, their use cases, and various methods to declare a variable in TypeScript.
In the above examples, we have discussed different use cases for using global variables in TypeScript to simplify data sharing across different parts of an application.

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.