TypeScript Variables

1️⃣ What Are Variables in TypeScript?

A variable is a container for storing values. In TypeScript, variables must have a specific data type.

✔ Example of a variable in TypeScript:

let message: string = "Hello, TypeScript!";
console.log(message);

✅ message is a variable that stores a string value.

2️⃣ Declaring Variables in TypeScript

TypeScript provides three ways to declare variables:
let – Block-scoped variable (Preferred)
const – Block-scoped, cannot be reassigned
var – Function-scoped (Not recommended)

KeywordScopeReassignment Allowed?Hoisting
letBlock✅ YesNo
constBlock❌ NoNo
varFunction✅ Yes (Avoid using)Yes

Let’s look at examples of each.

3️⃣ Using let in TypeScript

let is the most commonly used keyword for declaring variables.

Example:

let userName: string = "Alice";
console.log(userName);

✅ userName is a string variable that can be changed later.

Updating the variable:

let score: number = 100;
score = 150; // ✅ Allowed
console.log(score); // Output: 150

🔹 let is block-scoped

let variables are only accessible inside the block where they are declared.

if (true) {
let city: string = "New York";
console.log(city); // ✅ Works
}
console.log(city); // ❌ Error: city is not defined

Best Practice: Always prefer let over var.

4️⃣ Using const in TypeScript

const is used when you don’t want to change a variable’s value.

Example:

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

🚫 Reassigning a const variable gives an error:

const country: string = "India";
country = "USA"; // ❌ Error: Cannot assign to 'country' because it is a constant.

🔹 const is block-scoped

if (true) {
const language: string = "TypeScript";
console.log(language); // ✅ Works
}
console.log(language); // ❌ Error: language is not defined

Best Practice: Use const for values that never change (e.g., API URLs, configuration values).

5️⃣ Using var in TypeScript (Not Recommended)

var was used before ES6, but it has many issues, so avoid using it.

Example of var:

var age: number = 25;
console.log(age);

🚫 Why var is bad?
✔ It ignores block scope, causing unpredictable errors.
✔ It gets hoisted, meaning it can be used before declaration.

console.log(car);  // Output: undefined (Hoisting issue)
var car: string = "BMW";

Best Practice: Never use var, always prefer let or const.

6️⃣ Variable Type Annotations in TypeScript

TypeScript allows you to specify data types for variables. This is called type annotation.

Data TypeExample
stringlet name: string = “John”;
numberlet age: number = 25;
booleanlet isStudent: boolean = true;
anylet value: any = 10;
arraylet numbers: number[] = [1, 2, 3];

✔ Examples of different data types:

let username: string = "Alice";  // String
let score: number = 95.5; // Number
let isPassed: boolean = true; // Boolean
let data: any = "Hello"; // Any type (Avoid using)
let numbers: number[] = [1, 2, 3]; // Array

🚫 Avoid using any type because it removes type safety.

7️⃣ TypeScript Variables with Union Types

Union types allow a variable to store multiple types.

Example:

let id: number | string;
id = 101; // ✅ Valid
id = "TS101"; // ✅ Valid

Best Practice: Use union types when a variable needs to hold different types.

8️⃣ TypeScript Variables with Default Values

Variables can have default values in TypeScript.

✔ Example:

let color: string = "blue";  // Default value
console.log(color); // Output: blue

✔ Example with functions:

function greet(name: string = "User") {
console.log(`Hello, ${name}!`);
}
greet(); // Output: Hello, User!
greet("John"); // Output: Hello, John!

Best Practice: Use default values to handle cases when no value is provided.

🔟 Best Practices for TypeScript Variables

✔ Use let for variables that can change.
✔ Use const for values that never change.
✔ Avoid var because it has scope issues.
✔ Always define the correct data type.
✔ Use union types for flexible variables.

Leave a Comment

BoxofLearn