TypeScript supports let, const, and var to declare variables.let is block-scoped and mutable. const is block-scoped and immutable (binding only). Avoid using var as it is function-scoped and can lead to confusing bugs.
let count = 10;
const name = "Alice";
var oldWay = true; // not recommendedTypeScript allows you to explicitly declare a variable’s type using a colon after the variable name:
let age: number = 30;
let isOnline: boolean = true;
let message: string = "Hello TypeScript";If a variable is initialized with a value, TypeScript infers the type automatically:
let username = "Charlie"; // inferred as string
username = "Bob"; // ✅
username = 42; // ❌ Error: Type 'number' is not assignable to type 'string'Variables declared with let can be reassigned. const variables cannot be reassigned, but objects and arrays declared with const can still be mutated.
const scores = [10, 20, 30];
scores.push(40); // ✅ valid mutation
scores = [1, 2, 3]; // ❌ Error: Cannot reassign a constconst whenever possible to prevent accidental reassignment.let only when you need to change the value later.var unless required for compatibility.Ask the AI if you need help understanding or want to dive deeper in any topic