How to use var, let or const at the Top Level In Typescript

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();  // Accessible here


Output:

I am a global variable using let 
42
I am a global variable using var

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
  • Using window Object in Browser Environments
  • Using a Namespace or Module
  • Using declare Keyword

Similar Reads

Using var, let or const at the Top Level

Declare a variable with var, let or const at the top level of your script....

Using window Object in Browser Environments

...

Using a Namespace or Module

Assign a property to the window object for global accessibility in browsers....

Using declare Keyword

...