Skip to main content

Module 4: Interfaces

Interfaces define contracts for objects and classes in TypeScript. They describe the shape of data and enforce type safety.


1. Basic Interface

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

let user: User = {
name: "Alice",
age: 25,
email: "alice@example.com"
};

2. Optional Properties

interface Product {
id: number;
name: string;
description?: string; // Optional
price: number;
}

let product1: Product = {
id: 1,
name: "Laptop",
price: 999
}; // ✅ description is optional

3. Readonly Properties

interface Point {
readonly x: number;
readonly y: number;
}

let point: Point = { x: 10, y: 20 };
// point.x = 30; // ❌ Error: Cannot assign to 'x'

4. Function Types in Interfaces

interface MathOperation {
(a: number, b: number): number;
}

let add: MathOperation = (x, y) => x + y;
let multiply: MathOperation = (x, y) => x * y;

5. Indexable Types

interface StringArray {
[index: number]: string;
}

let colors: StringArray = ["red", "green", "blue"];
let firstColor: string = colors[0];

6. Extending Interfaces

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

interface Employee extends Person {
employeeId: number;
department: string;
}

let emp: Employee = {
name: "Bob",
age: 30,
employeeId: 1001,
department: "IT"
};

7. Interface vs Type Alias

// Interface
interface IUser {
name: string;
age: number;
}

// Type Alias
type TUser = {
name: string;
age: number;
};
When to Use What
  • Interface: For object shapes, classes, and when extending
  • Type Alias: For unions, tuples, primitives

Key Takeaways

✅ Interfaces define object shapes
✅ Use optional (?) and readonly modifiers
✅ Interfaces can extend other interfaces
✅ Great for API contracts and data models


Next Steps

In Module 5, we'll learn about Classes in TypeScript with access modifiers, inheritance, and abstract classes.