Lesson 8 of 20

Interfaces

Defining Interfaces

Interfaces define the structure of an object — what properties and methods it must have. They are one of TypeScript's most powerful features.

Example
// Basic interface
interface User {
  name: string;
  email: string;
  age: number;
}

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

// Optional and readonly properties
interface Product {
  readonly id: number;
  name: string;
  price: number;
  description?: string; // optional
}

Extending Interfaces

Interfaces can extend other interfaces, inheriting their properties. This promotes code reuse.

Example
interface Animal {
  name: string;
  sound: string;
}

interface Pet extends Animal {
  owner: string;
}

const dog: Pet = {
  name: "Rex",
  sound: "Woof",
  owner: "John"
};

// Extend multiple interfaces
interface Timestamps {
  createdAt: Date;
  updatedAt: Date;
}

interface Post extends User, Timestamps {
  title: string;
  content: string;
}

Interfaces with Methods

Interfaces can describe methods as well as properties.

Example
interface Calculator {
  add(a: number, b: number): number;
  subtract(a: number, b: number): number;
}

const calc: Calculator = {
  add: (a, b) => a + b,
  subtract: (a, b) => a - b
};

// Index signatures
interface StringMap {
  [key: string]: string;
}

const colors: StringMap = {
  red: "#ff0000",
  green: "#00ff00",
  blue: "#0000ff"
};