TypeScript Lesson 5: Interfaces

📘 TypeScript CourseLesson 5 of 12 · 42% complete

Interfaces define the shape of objects. They’re how TypeScript describes what data looks like — like a blueprint or contract.

Basic Interface

interface User {
  id: number;
  name: string;
  email: string;
  age?: number;        // optional property
  readonly role: string; // can't be reassigned after creation
}

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

user.role = "user";  // ❌ Error: readonly
user.name = "Bob";   // ✅ OK

Interface Methods

interface Animal {
  name: string;
  age: number;
  speak(): string;               // method signature
  eat(food: string): void;
  describe?(detail: string): string; // optional method
}

const dog: Animal = {
  name: "Rex",
  age: 3,
  speak: () => "Woof!",
  eat: (food) => console.log(`${dog.name} eats ${food}`)
};

Extending Interfaces

interface Entity {
  id: number;
  createdAt: Date;
}

interface User extends Entity {
  name: string;
  email: string;
}

interface Admin extends User {
  permissions: string[];
  canDelete: boolean;
}

// Admin has ALL properties: id, createdAt, name, email, permissions, canDelete

🏋️ Practice Task

Design a blogging platform. Create interfaces: Author (id, name, email, bio?), Tag (id, name, slug), Post (id, title, content, author: Author, tags: Tag[], publishedAt: Date, draft?: boolean). Create example data matching each interface.

💡 Hint: When you type post.author it should autocomplete with .name, .email etc — that’s TypeScript helping you.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *