runtime.boot

Full Stack Systems
Production Mindset

CodeWithMihir

Engineering thoughtful products from interface to infrastructure.

CodeWithMihir

TypeScript Tutorial

Extending Interfaces in TypeScript

Learn how to extend interfaces in TypeScript, including single extension, multiple extension, method inheritance, overriding rules, and practical examples.

Welcome back! I am Mihir, and in this lesson we will learn how to extend interfaces in TypeScript.

Extending interfaces lets you build bigger object shapes from smaller ones.


Basic Interface Extension

interface Person {
  name: string;
}

interface Employee extends Person {
  employeeId: number;
}

const employee: Employee = {
  name: "Mihir",
  employeeId: 101,
};

Employee includes everything from Person.


Extending Multiple Interfaces

An interface can extend more than one interface.

interface HasId {
  id: number;
}

interface HasEmail {
  email: string;
}

interface User extends HasId, HasEmail {
  name: string;
}

Now User needs id, email, and name.

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

Extending Interfaces with Methods

interface Reader {
  read(): string;
}

interface Writer extends Reader {
  write(value: string): void;
}

const file: Writer = {
  read() {
    return "content";
  },
  write(value) {
    console.log(value);
  },
};

Writer must include both read and write.


Adding Optional Properties

interface BaseProduct {
  id: number;
  name: string;
}

interface DigitalProduct extends BaseProduct {
  downloadUrl?: string;
}

downloadUrl is optional, but id and name are still required.


Extending for API Models

This pattern is useful when API models share common fields.

interface BaseEntity {
  id: number;
  createdAt: string;
  updatedAt: string;
}

interface BlogPost extends BaseEntity {
  title: string;
  content: string;
}

interface Comment extends BaseEntity {
  postId: number;
  message: string;
}

Each model reuses the same base fields.


Property Type Must Be Compatible

Be careful when changing inherited properties.

interface Product {
  id: number;
}

interface BrokenProduct extends Product {
  id: string;
}

This is invalid because id was already defined as number.


Interface Extension vs Intersection

This interface:

interface Admin extends User {
  role: "admin";
}

Is similar to this type:

type Admin = User & {
  role: "admin";
};

Both are useful. Interfaces are often clearer when you are modeling object inheritance.


Quick Recap

  • extends lets one interface build on another.
  • An interface can extend multiple interfaces.
  • Inherited properties are still required unless they were optional.
  • You cannot change an inherited property to an incompatible type.
  • Extension is great for shared API and domain models.

Next up, we will learn Intersection Types →, a flexible way to combine types with &.