TypeScript Variables

let, const, and var

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 recommended

Type Annotations

TypeScript 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";

Inferred Types

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'

Reassignment and Mutability

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 const

Best Practices

  • Use const whenever possible to prevent accidental reassignment.
  • Use let only when you need to change the value later.
  • Avoid using var unless required for compatibility.
  • Use type annotations for clarity when types aren't obvious.

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic