Open In App

Variables in TypeScript

Last Updated : 09 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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;
  • Type and value are defined together.
  • name is a variable of type string.
  • age is a constant of type number.

2. Declare Type Without Value

typescript
let city: string;
console.log(city); 
  • Only the type is defined; the value is undefined by default.

3. Declare Value Without Type

JavaScript
let country = 'India';
console.log(country); 
  • The type is inferred as string, and the value is initialized to 'India'.

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

  • Function testVar() is declared.
  • Inside the function, a variable globalVar is declared with var.
  • var gives it function scope, meaning it's only available inside the function.
  • console.log(globalVar) prints the value: "I am a function-scoped variable".
  • The function is called with testVar(), and the output is shown.
  • Outside the function, globalVar isn't accessible.

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

  • let count = 5; declares a variable count.
  • Inside the if block, a new variable message is declared with let.
  • let gives message block-level scope, meaning it's only available within the if block.
  • console.log(message); prints "Count is positive" inside the block.
  • Outside the block, trying to access message results in an error because it’s out of scope.

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

  • const country = "India"; declares a constant variable country and assigns it the value "India".
  • Since it's declared with const, it cannot be reassigned.
  • Attempting to change its value with country = "USA"; results in an error.
  • console.log(country); prints "India" to the console.

Note:

  • Variable names can contains alphabets both Upper-case as well as Lower-case and digits also.
  • Variable names can’t start with a digit.
  • We can use _ and $ special characters only, apart from these other special characters are not allowed.

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, ${name}! You are ${age} years old.`;
}

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

Output

Hello, Arjun! You are 25 years old.

In this example

  • userName: string specifies that the userName variable must hold a string value.
  • age: number specifies that the age variable must hold a number value.
  • isActive: boolean specifies that isActive must be a boolean.
  • The function greetUser(name: string, age: number) uses type annotations for both parameters and the return type to ensure type safety.

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

  • The function testLocalScope() is declared.
  • Inside the function, a variable localVar is declared with let.
  • let gives localVar block-level scope, meaning it’s only available inside the function.
  • console.log(localVar); inside the function prints "I am local".
  • Trying to access localVar outside the function results in an error because it’s out of scope.

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

  • A variable globalVar is declared outside the function and assigned the value 10.
  • The function displayGlobalVar() is declared.
  • Inside the function, console.log(globalVar) prints the value of globalVar, which is 10.
  • The function displayGlobalVar() is called, showing the value of globalVar.

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

  • The class Employee has: A property salary set to 50000. A method printSalary() that prints the salary.
  • An object emp is created from the Employee class.
  • Calling emp.printSalary() prints the salary.

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(); 
  • globalVar is a global variable, accessible throughout the program.
  • classVar is a private class-level variable, accessible only within the Geeks class.
  • localVar is a local variable, accessible only within the assignNum method.

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


Next Article

Similar Reads