How to Create a Global Variable in TypeScript ?
Last Updated :
10 Jan, 2024
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:
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.
Javascript
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();
|
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.
Javascript
(window as any).browserGlobal =
"I am a global variable accessible in browsers" ;
function useBrowserGlobal() {
console.log((window as any).browserGlobal);
}
useBrowserGlobal();
|
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.
Javascript
namespace GlobalNamespace {
export let globalVariable: string = "I am a global variable" ;
}
function useGlobalNamespace() {
console.log(GlobalNamespace.globalVariable);
}
useGlobalNamespace();
|
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.
Javascript
declare var declaredGlobal: boolean;
function useDeclaredGlobal() {
console.log(declaredGlobal);
}
useDeclaredGlobal();
|
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
Share your thoughts in the comments
Please Login to comment...