JavaScript Development Space

How to Declare and Use Global Variables in TypeScript

TypeScript provides a structured way to declare and use global variables while ensuring type safety. Global variables can be accessed across your application, but managing them properly is essential to avoid conflicts and maintain code clarity.

Steps to Declare Global Variables in TypeScript

1. Create a Global Declaration File

TypeScript uses declaration files (.d.ts) to define global variables. Create a file, typically named globals.d.ts, in your project directory.

touch globals.d.ts

2. Define the Global Variable

Inside the globals.d.ts file, use the declare keyword to define your global variable. You can specify its type for type checking.

ts
1 declare const API_URL: string;

This tells TypeScript that a global variable API_URL exists and is of type string.

3. Set the Global Variable

Set the global variable in your JavaScript or TypeScript runtime. For example, in a script tag in an HTML file or at the entry point of your application:

Example in HTML:

html
1 <script>
2 window.API_URL = "https://api.example.com";
3 </script>

Example in TypeScript:

ts
1 (globalThis as any).API_URL = "https://api.example.com";

4. Access the Global Variable

You can now access the global variable anywhere in your TypeScript code without re-declaring it.

ts
1 console.log(`API Endpoint: ${API_URL}`);

5. Optional: Extend Existing Global Interfaces

To ensure better integration with existing global objects like window, you can extend their interfaces.

ts
1 // globals.d.ts
2 interface Window {
3 API_URL: string;
4 }

Set the variable in the browser's window object:

ts
1 window.API_URL = "https://api.example.com";

Access it:

ts
1 console.log(window.API_URL);

Tips for Managing Global Variables

  • Avoid Overusing Globals: Use them sparingly to reduce potential conflicts.
  • Namespace Grouping: Group related variables under a namespace to avoid clutter.
    ts
    1 declare namespace MyApp {
    2 const CONFIG: {
    3 API_URL: string;
    4 VERSION: string;
    5 };
    6 }
  • Use Environment Variables: Tools like dotenv allow you to manage configurations without hardcoding global variables.

Conclusion

Global variables in TypeScript are easy to declare and use when structured correctly. By using declaration files, extending global interfaces, and adhering to best practices, you can ensure your application remains maintainable and type-safe.

JavaScript Development Space

© 2025 JavaScript Development Space - Master JS and NodeJS. All rights reserved.