Variables in TypeScript (original) (raw)

Last Updated : 21 Jan, 2025

Variables in TypeScript are used to store data values, acting as named memory locations that can hold numbers, strings, booleans, or other types of data.

Variable Declaration in TypeScript

In TypeScript, variables are used to store data values, with modern declarations offering strong typing and better scoping rules. Let's explore how variables are declared in TypeScript.

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); // Output: undefined

`

3. Declare Value Without Type

JavaScript `

let country = 'India'; console.log(country); // Output: India

`

Keywords for Variable Declaration

1. var

Traditionally used in JavaScript, var is function-scoped and can lead to unexpected behavior due to hoisting.

JavaScript `

var globalVar: number = 10; console.log(globalVar); // Output: 10

`

2. let

Introduced to provide block-level scoping, let confines the variable's scope to the block in which it's defined.

JavaScript `

let blockScoped: string = 'TypeScript'; console.log(blockScoped); // Output: TypeScript

`

3. const

Similar to let in terms of block scoping, const is used for variables that should not be reassigned after their initial assignment.

JavaScript `

const PI: number = 3.14; console.log(PI); // Output: 3.14

`

Note:

Type Annotations in TypeScript

TypeScript allows explicit type definitions, enhancing code clarity and type safety.

JavaScript `

let employeeName: string = 'John Doe'; let employeeAge: number = 30; const company: string = 'TechCorp';

`

Variable Scopes in TypeScript

1. Local Scope

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

JavaScript `

function example() { let localVar: number = 42; console.log(localVar); // Output: 42 }

`

2. Global Scope

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

JavaScript `

let globalVar: string = 'Accessible everywhere'; console.log(globalVar); // Output: Accessible everywhere

`

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: Salary: 50000

``

**Example of Variables in TypeScript

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