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.
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.
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:
1 <script>2 window.API_URL = "https://api.example.com";3 </script>
Example in TypeScript:
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.
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.
1 // globals.d.ts2 interface Window {3 API_URL: string;4 }
Set the variable in the browser's window
object:
1 window.API_URL = "https://api.example.com";
Access it:
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.
ts1 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.