Variables in TypeScript (original) (raw)

Last Updated : 09 Jun, 2025

In **TypeScript, **variables are used to store values that can be referenced and manipulated throughout your code. TypeScript offers three main ways to declare variables: let, **const, and **var. Each has **different behavior when it comes to reassigning values and scoping, allowing us to write more **reliable and **understandable code.

Types of Variable Declarations

In TypeScript, we can declare variables in several ways.

1. Declare Type and Value in a Single Statement

typescript `

let name: string = 'Amit'; const age: number = 25;

`

2. Declare Type Without Value

typescript `

let city: string; console.log(city);

`

3. Declare Value Without Type

JavaScript `

let country = 'India'; console.log(country);

`

Variable Declaration Keywords in TypeScript

TypeScript allows you to declare variables using three keywords: var, let, and const. Here's a breakdown of how each works:

1. var

var is function-scoped and can lead to unexpected behavior due to hoisting. It’s accessible throughout the function in which it’s declared but has function-level scoping.

JavaScript `

function testVar() { var globalVar = "I am a function-scoped variable"; console.log(globalVar);
} testVar();

`

**Output

I am a function-scoped variable

**In this example

**Note => Avoid using var in modern TypeScript due to its unpredictable behavior.

2. let

let provides block-level scoping, meaning it is confined to the block (i.e., loop or condition) in which it is declared. It helps prevent redeclaration within the same scope and reduces issues related to hoisting.

JavaScript `

let count = 5; if (count > 0) { let message = "Count is positive"; console.log(message); } // console.log(message); // Error: message is not accessible here

`

**Output

Count is positive

**In this example

3. const

Similar to let in terms of scoping, const is used for variables that should not be reassigned after their initial value. Attempting to reassign a const variable results in a compile-time error.

JavaScript `

const country = "India"; // country = "USA"; // Error: Cannot assign to 'country' because it is a constant console.log(country);

`

**Output

India

**In this example

Note:

Type Annotations in TypeScript

Type annotations allow you to explicitly define the type of a variable, improving code clarity and reducing the risk of errors. Using explicit types helps TypeScript catch errors during development and ensures better maintainability.

**Now let's understand this with the help of example:

JavaScript ``

let userName: string = "Arjun";
let age: number = 25;
let isActive: boolean = true;

function greetUser(name: string, age: number): string { return Hello, <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi></mrow><mo stretchy="false">!</mo><mi>Y</mi><mi>o</mi><mi>u</mi><mi>a</mi><mi>r</mi><mi>e</mi></mrow><annotation encoding="application/x-tex">{name}! You are </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord"><span class="mord mathnormal">nam</span><span class="mord mathnormal">e</span></span><span class="mclose">!</span><span class="mord mathnormal" style="margin-right:0.22222em;">Y</span><span class="mord mathnormal">o</span><span class="mord mathnormal">u</span><span class="mord mathnormal">a</span><span class="mord mathnormal">re</span></span></span></span>{age} years old.; }

let greeting = greetUser(userName, age); console.log(greeting);

``

**Output

Hello, Arjun! You are 25 years old.

**In this example

Variable Scopes in TypeScript

Understanding variable scope is crucial for managing the accessibility and lifespan of variables in TypeScript. There are three main types of scopes:

1. Local Scope

Variables declared within a function or block are accessible only within that function or block.

JavaScript `

function testLocalScope() { let localVar = "I am local"; console.log(localVar);
} // console.log(localVar); // Error: localVar is not defined outside the function

`

**Output

I am local

**In this example

2. Global Scope

Variables declared outside any function or block are accessible throughout the entire program.

JavaScript `

let globalVar = 10;
function displayGlobalVar() { console.log(globalVar); } displayGlobalVar();

`

**Output

10

**In this example

3. Class Scope

Variables declared within a class are accessible to all members (methods) of that class.

JavaScript ``

class Employee { salary: number = 50000; printSalary(): void { console.log(Salary: ${this.salary}); } }

const emp = new Employee(); emp.printSalary();

``

**Output

50000

**In this example

**Now let's understand variables with this example:

JavaScript `

let globalVar: number = 10;

class Geeks { private classVar: number = 11;

assignNum(): void {
    let localVar: number = 12;
    console.log('Local Variable: ' + localVar);
}

}

console.log('Global Variable: ' + globalVar);

let obj = new Geeks(); obj.assignNum();

`

**Output:

**Global Variable: 10
**Local Variable: 12

Conclusion

In TypeScript, variables are essential for **storing and manipulating data. By using **let, const, and var, TypeScript allows us to define variables with different scoping and **reassignment rules, **enhancing code reliability. Understanding type annotations helps **catch errors **early, improving code clarity