Interface Extension

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 3 min

TL;DR

You can copy the properties of one interface into another using the extends keyword. This promotes reusability, keeping your types DRY (Don’t Repeat Yourself), and accurately models object-oriented inheritance.

Mental Model

How It Works

When an interface extends another interface, it inherits all of its properties.
You can extend multiple interfaces at the same time by separating them with commas.

If the extending interface tries to redefine a property from the base interface, it must be assignable to the base property type (i.e., you can narrow it, but you can’t completely change it).

Example

interface Shape {
    color: string;
}

interface HasArea {
    calculateArea(): number;
}

// Extending multiple interfaces!
interface Square extends Shape, HasArea {
    sideLength: number;
}

const mySquare: Square = {
    color: "blue",
    sideLength: 10,
    calculateArea() {
        return this.sideLength * this.sideLength;
    }
};

Common Interview Questions

Can you extend a type alias with an interface?

Yes! An interface can extend a type alias (as long as the type alias represents an object shape). And vice versa, a type alias can intersect (&) an interface.

type PointType = { x: number; y: number };
interface Point3D extends PointType { z: number; } // Perfectly valid!

What happens if you try to change the type of an inherited property?

If you try to change it to an incompatible type, TypeScript throws an error.

interface Animal { name: string | null; }

// VALID: Narrowing the type
interface Dog extends Animal { name: string; } 

// ERROR: Incompatible type
// interface Cat extends Animal { name: number; }