In TypeScript, you can define a global variable by declaring it outside of any function, class, or module scope. To ensure that TypeScript recognizes the variable as a global and to avoid issues with the module system, you should use the declare keyword if you're augmenting an existing global variable or the global namespace for adding new global variables.
Here are a few ways to define a global variable in TypeScript:
Using declare for existing globals:
If you want to add a type to an existing global variable that is defined in a JavaScript file or through a library you're using, you can use the declare keyword. This doesn't create a new variable; it just tells TypeScript about the type of an existing global variable.
typescript
// Assuming `myGlobal` is already defined elsewhere (e.g. in a script tag in HTML)
declare var myGlobal: any;
myGlobal = 'This is a global variable';
Using globalThis:
The globalThis object provides a standard way to access the global this value across environments. You can use it to define a global variable that is accessible everywhere.
typescript
globalThis.myGlobal = 'This is a global variable';
Using window in browsers or global in Node.js:
In a browser environment, you can attach properties to the window object, and in Node.js, you can use the global object. Keep in mind that these are environment-specific.
typescript
// In a browser
window.myGlobal = 'This is a global variable';
// In Node.js
global.myGlobal = 'This is a global variable';
Using a namespace for new globals:
You can use TypeScript's namespace to add new global variables that TypeScript is aware of. This is often used in definitions (.d.ts) files.
typescript
// In a .d.ts file or at the top level of a module
declare namespace NodeJS {
interface Global {
myGlobal: string;
}
}
// Now TypeScript knows about `global.myGlobal`
global.myGlobal = 'This is a global variable';
Using a global.d.ts file:
You can create a global.d.ts file in your project and declare global variables there. This is useful for type declarations that should be available everywhere in your project.
typescript
// In global.d.ts
declare var myGlobal: string;
// Now you can use `myGlobal` anywhere in your project
myGlobal = 'This is a global variable';
Remember that global variables should be used sparingly and carefully, as they can lead to code that is harder to maintain and understand. Generally, it's better to encapsulate your code within modules and classes and explicitly import and export what you need.