📘 TypeScript

TypeScript Interfaces and Type Aliases

Defining an Interface

interface User {
    id: number;
    name: string;
    email: string;
}

const user: User = {
    id: 1,
    name: "Alice",
    email: "alice@example.com"
};

Optional and Readonly Properties

interface Product {
    readonly id: number;     // cannot change after creation
    name: string;
    price: number;
    description?: string;    // optional
}

const laptop: Product = {
    id: 101,
    name: "Laptop Pro",
    price: 1299.99
};
// laptop.id = 200;  // ❌ Error: readonly

Extending Interfaces

interface Animal {
    name: string;
    age: number;
}

interface Dog extends Animal {
    breed: string;
    bark(): void;
}

const rex: Dog = {
    name: "Rex",
    age: 3,
    breed: "Labrador",
    bark() { console.log("Woof!"); }
};

Interface vs Type Alias

// interface — extendable, declaration merging
interface Point { x: number; y: number; }
interface Point { z?: number; }  // merged!

// type alias — more powerful, supports unions
type Shape = Circle | Rectangle;
type Circle = { kind: "circle"; radius: number };
type Rectangle = { kind: "rect"; w: number; h: number };

Index Signatures

interface StringMap {
    [key: string]: string;
}

const config: StringMap = {
    host: "localhost",
    port: "5432",
    db: "myapp"
};

interface NumberCache {
    [key: string]: number;
}
const cache: NumberCache = {};
cache["hits"] = 100;