Global variables let you store information that many parts of your program can use. This helps share data easily across different functions or files.
0
0
Declaring global variables in Typescript
Introduction
When you want to keep a value accessible everywhere in your program, like a configuration setting.
When multiple functions need to read or update the same data, such as a score in a game.
When you want to share constants or settings across different files without passing them around.
When you need to keep track of a state that affects the whole app, like user login status.
Syntax
Typescript
declare global {
var variableName: type;
}
// or simply
var variableName: type = value;Use declare global when adding variables to the global scope in TypeScript modules.
Using var declares a global variable if done outside any function or module.
Examples
This creates a global variable
count with the number 0.Typescript
var count: number = 0;
This adds
appName as a global string variable inside a module.Typescript
declare global {
var appName: string;
}
appName = "MyApp";Here,
isLoggedIn is global and can be changed inside functions.Typescript
var isLoggedIn: boolean; function login() { isLoggedIn = true; }
Sample Program
This program declares a global variable globalMessage and prints it inside a function.
Typescript
var globalMessage: string = "Hello, world!"; function showMessage() { console.log(globalMessage); } showMessage();
OutputSuccess
Important Notes
Global variables can be changed from anywhere, so use them carefully to avoid bugs.
Prefer const or let inside functions or blocks to limit variable scope.
In TypeScript modules, use declare global to add variables to the global scope safely.
Summary
Global variables store data accessible everywhere in your program.
Use var outside functions or declare global in modules to create globals.
Be careful with globals to keep your code easy to understand and debug.