How to Create a Global Variable in TypeScript ?
To create a global variable in TypeScript, we have multiple approaches. In this article, we are going to learn how to create a global variable in TypeScript.
Below are the approaches used to create a global variable in TypeScript:
Table of Content
Using var, let
or const
at the Top Level
Declare a variable with var, let
or const
at the top level of your script.
Example: In this example, we are using var, let, and const to create a global variable in TypeScript.
var globalVar: string = "I am a global variable using var";
let globalLet: string = "I am a global variable using let";
const globalConst: number = 42;
function useGlobalVarLetAndConst() {
console.log(globalLet, globalConst, globalVar);
}
useGlobalVarLetAndConst(); // Accessible here
Output:
I am a global variable using let
42
I am a global variable using var
Using window
Object in Browser Environments
Assign a property to the window
object for global accessibility in browsers.
Example: In this example, we are using window
Object in Browser Environments to create a global variable in TypeScript.
// Using the window object in browser environments
(window as any).browserGlobal =
"I am a global variable accessible in browsers";
function useBrowserGlobal() {
console.log((window as any).browserGlobal);
}
useBrowserGlobal(); // Accessible here (in browser environments)
Output:
I am a global variable accessible in browsers
Using a Namespace or Module
Place the variable inside a namespace or module for organized global scope.
Example: In this example, we are using a Namespace or Module to create a global variable in TypeScript.
// Using a namespace or module
namespace GlobalNamespace {
export let globalVariable: string = "I am a global variable";
}
function useGlobalNamespace() {
console.log(GlobalNamespace.globalVariable);
}
useGlobalNamespace(); // Accessible here
// Using a namespace or module
namespace GlobalNamespace {
export let globalVariable: string = "I am a global variable";
}
function useGlobalNamespace() {
console.log(GlobalNamespace.globalVariable);
}
useGlobalNamespace(); // Accessible here
Output:
I am a global variable
Using declare
Keyword
Use the declare
keyword for external global variables without a specific implementation.
Example: In this example, we are using declare
Keyword to create a global variable in TypeScript.
// Using declare keyword
declare var declaredGlobal: boolean;
function useDeclaredGlobal() {
console.log(declaredGlobal);
}
useDeclaredGlobal(); // Accessible here
Output:
The output will depend on the actual value assigned to externalLibraryVar
at runtime. For example, if it is defined externally before calling useExternalVariable()
, the output might look like this:
[declaredGlobal value]
If declaredGlobal is not defined, you might encounter a runtime error similar to:
Uncaught ReferenceError: declaredGlobal is not defined