</>
Skip to content
TypeScript lessons (6/31)

TypeScript — Variables

let vs const

// const: cannot reassign, but object properties can change
const name = "Alice";
// name = "Bob"; // Error: cannot reassign

const person = { name: "Alice", age: 30 };
person.name = "Bob"; // OK: modifying property
// person = {};      // Error: cannot reassign

// let: block-scoped, can reassign
let count = 0;
count = 10; // OK

// var: function-scoped (avoid)
var oldWay = "don't use";

Type inference

TypeScript automatically infers types:

let name = "Alice";     // inferred as string
let age = 30;           // inferred as number
let active = true;      // inferred as boolean

// Return type is inferred
function add(a: number, b: number) {
    return a + b; // inferred as number
}

// Array type is inferred
const nums = [1, 2, 3]; // inferred as number[]

When to use explicit types

// Good: explicit type for function parameters
function greet(name: string): string {
    return `Hello, ${name}`;
}

// Good: explicit type when inference isn't enough
let input: string | null = null;

// Good: explicit type for public API
export function processData(data: UserInput): Result {
    // ...
}

// Fine: inference is OK for local variables
let x = 5; // number is obvious
const items = [1, 2, 3]; // number[] is obvious

Destructuring

// Object destructuring
const { name, age } = { name: "Alice", age: 30 };

// Rename
const { name: userName, age: userAge } = { name: "Alice", age: 30 };

// Default values
const { city = "Unknown" } = { name: "Alice" };

// Rest
const { name: n, ...rest } = { name: "Alice", age: 30, city: "NYC" };

// Array destructuring
const [first, second, third] = [1, 2, 3];

// Skip elements
const [, , thirdOnly] = [1, 2, 3];

// Rest
const [head, ...tail] = [1, 2, 3, 4, 5];

Spread operator

// Array spread
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];

// Object spread
const defaults = { theme: "dark", lang: "en" };
const userPrefs = { theme: "light" };
const config = { ...defaults, ...userPrefs };
// { theme: "light", lang: "en" }

Block scoping

// const and let are block-scoped
if (true) {
    const x = 10;
    let y = 20;
}
// console.log(x); // Error: x is not defined
// console.log(y); // Error: y is not defined

// Loop scoping
for (let i = 0; i < 5; i++) {
    setTimeout(() => console.log(i), 100);
}
// Logs 0, 1, 2, 3, 4 (each i is scoped to its iteration)

// var would log 5, 5, 5, 5, 5 (shared i)

Const assertions (as const)

// Freeze the object at the type level
const config = {
    apiUrl: "https://api.example.com",
    timeout: 5000
} as const;
// type: { readonly apiUrl: "https://api.example.com"; readonly timeout: 5000 }

// Tuple as const
const colors = ["red", "green", "blue"] as const;
// type: readonly ["red", "green", "blue"]

// Enum alternative
const Direction = {
    Up: "UP",
    Down: "DOWN",
    Left: "LEFT",
    Right: "RIGHT"
} as const;
type Direction = typeof Direction[keyof typeof Direction];

Satisfies operator (TS 4.9+)

// Type check without widening
type Colors = "red" | "green" | "blue";

const palette = {
    red: [255, 0, 0],
    green: "#00ff00",
    blue: [0, 0, 255]
} satisfies Record<Colors, string | number[]>;

// palette.red is number[] (not string | number[])
console.log(palette.red.map(c => c.toString()));

Global declarations

// Declare global variables
declare const API_URL: string;
declare function fetchJSON(url: string): Promise<unknown>;

// Ambient module declarations
declare module "some-untyped-lib" {
    export function doSomething(): void;
}

Mini Practice

Write TypeScript code that:

  1. Uses const with as const for a configuration object
  2. Demonstrates destructuring with defaults
  3. Shows block scoping differences between let and var
  4. Uses the spread operator for arrays and objects

Up Next

In the next lesson, you'll learn about Functions — types, overloads, and generics.

Related Topics

Frequently Asked Questions about Variables

What is Variables in TypeScript?

Variables is a fundamental concept in TypeScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Variables?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Variables.

Why is Variables important in TypeScript?

Variables is essential for TypeScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.