Typescript Foundations / Objects & Interfaces

Interface extension (extends)

πŸ‘‰ When one interface inherits properties from another, it's called extension.

πŸ‘‰ Use the extends keyword to create a new interface based on an existing one.


βœ… Basic Syntax

interface Base {
  id: number;
}

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

Now User has all properties from both Base and itself:

const u1: User = {
  id: 1,
  name: "Tisha",
  email: "tisha@example.com"
};

✨ Why Use Extension?

βœ… DRY (Don't Repeat Yourself)

βœ… Promotes reusability

βœ… Helps with large-scale applications

βœ… Useful for OOP-style modeling (like base classes)


πŸ” Extending Multiple Interfaces

You can extend more than one interface by comma-separating them:

interface Timestamped {
  createdAt: Date;
  updatedAt: Date;
}

interface Identified {
  id: string;
}

interface Post extends Timestamped, Identified {
  title: string;
  content: string;
}
const blogPost: Post = {
  id: "p1",
  title: "Intro to TypeScript",
  content: "Great for large JS apps",
  createdAt: new Date(),
  updatedAt: new Date()
};

🧠 Optional and Readonly Properties Work Too

interface Person {
  readonly id: number;
  name: string;
  age?: number;
}

interface Employee extends Person {
  department: string;
}

βœ… Interface Extension with Methods

interface Animal {
  name: string;
  speak(): void;
}

interface Dog extends Animal {
  breed: string;
}

const pet: Dog = {
  name: "Tommy",
  breed: "Beagle",
  speak() {
    console.log("Woof!");
  }
};

πŸ” Interface vs Type with &

You can achieve similar behavior with type using intersection:

type A = { id: number };
type B = { name: string };
type C = A & B;

const obj: C = { id: 1, name: "Tisha" };

Feature

interface

type + &

Object extension

βœ… extends

βœ… &

Declaration merging

βœ…

❌

Non-object types

❌

βœ…


βœ… Summary

Concept

Syntax

Extend one interface

interface B extends A

Extend multiple

interface C extends A, B

Combine methods, optional & readonly

βœ… Supported

Reusable for large apps

βœ… Best practice