TypeScript Global Variables

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_HERE

This 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 Doe

Output:

Global Variable in TypeScript

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/myapp

This 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:

Declare global variable in TypeScript

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: dark

Output:

Define Global Variables in TypeScript

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:

  1. Use TypeScript’s type system: Always declare types for your global variables to prevent type errors.
  2. Minimize mutability: When possible, use const or readonly to avoid accidental changes to global variables.
  3. Document your globals: Add comments that explain the purpose of each worldwide variable and indicate who should modify it.
  4. Consider alternatives: For complex state management, consider using libraries like Redux or MobX instead of raw global variables.
  5. Namespace your globals: Group related globals together to avoid polluting the global namespace.
  6. 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.

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.