Published on

How to Create a Global Variable in TypeScript

Authors
  • Name
    Ripal & Zalak
    Twitter

How to Create a Global Variable in TypeScript

Global variables are often necessary in certain scenarios, such as maintaining shared state across modules or integrating with third-party libraries. However, creating and managing global variables in TypeScript requires some specific steps to ensure type safety and maintainability.

In this article, you'll learn:

  • The challenges of creating global variables in TypeScript.
  • Best practices for declaring and accessing global variables.
  • How to avoid common pitfalls while working with global variables.

Why TypeScript Handles Globals Differently

TypeScript enforces strong typing and modularity. Unlike JavaScript, where you can simply assign a property to window or declare a variable without let, var, or const, TypeScript requires explicit declarations for global variables to ensure type safety.

Steps to Create a Global Variable in TypeScript

1. Extending the Window Interface

If you're working in a browser environment, you can extend the Window interface to add your global property.

Example:

Create a global.d.ts file:

declare global {
  interface Window {
    myGlobalVariable: string
  }
}

Then, set the global variable in your code:

window.myGlobalVariable = 'Hello, TypeScript!'

console.log(window.myGlobalVariable) // Outputs: Hello, TypeScript!

2. Using declare var for Simpler Use Cases

If you want to directly define a global variable without attaching it to window, you can use declare var.

Example:

In your global.d.ts file:

declare var myGlobalVariable: string

In your main file:

myGlobalVariable = 'Hello, TypeScript!'

console.log(myGlobalVariable) // Outputs: Hello, TypeScript!

3. Using globalThis

TypeScript supports globalThis for accessing the global scope in a universal way (browser, Node.js, etc.).

Example:

declare global {
  var myGlobalVariable: string
}

globalThis.myGlobalVariable = 'Hello, TypeScript!'

console.log(globalThis.myGlobalVariable) // Outputs: Hello, TypeScript!

This approach works across environments, making it versatile for shared libraries or server-side code.

Best Practices for Global Variables in TypeScript

1. Use Global Variables Sparingly

Avoid excessive use of globals, as they can lead to unintended side effects and tight coupling between modules. Prefer modular design whenever possible.

2. Declare Globals in a Separate File

Keep all global declarations in a dedicated global.d.ts file. This improves maintainability and makes it easier for other developers to understand the available globals.

3. Use Namespaces for Grouping

If you have multiple related global variables, consider grouping them under a namespace to avoid clutter and potential naming conflicts.

Example:

declare global {
  namespace AppGlobals {
    var config: { [key: string]: string }
  }
}

AppGlobals.config = { theme: 'dark' }

console.log(AppGlobals.config.theme) // Outputs: dark

Common Pitfalls to Avoid

1. Not Using declare

Forgetting to declare the global variable leads to TypeScript errors.

// Error: 'myGlobalVariable' does not exist on type 'Window & typeof globalThis'
window.myGlobalVariable = 'Hello'

2. Using let or const Instead of var

let and const create block-scoped variables, which do not attach to the global object. Always use var for globals in the global scope.

// This will not attach to globalThis
let myGlobalVariable = 'Hello'

Conclusion

Creating global variables in TypeScript requires careful planning and adherence to best practices to ensure type safety and maintainability. By extending the Window interface, using declare, or leveraging globalThis, you can implement global variables effectively in your TypeScript projects.

When possible, aim to minimize the use of global variables and opt for modular or scoped designs instead.