TypeScript Course
TypeScript
/
Intermediate

Extending Interfaces

Definition

The `extends` keyword allows one interface to inherit all the properties of another interface, promoting reusability and DRY (Don't Repeat Yourself) code.

Explain Like I'm New

Imagine you have a basic 'Vehicle' blueprint (has wheels, has color). You want to build a 'Car' blueprint. Instead of rewriting 'wheels' and 'color', you tell the Car blueprint to 'extend' the Vehicle blueprint, automatically copying its requirements, and then you just add 'doors'.

Real World Example

A base `APIResponse` interface with `{ status: number, message: string }`, extended by a `UserResponse` interface that adds `{ data: User }`.

Common Use Cases

  • •Component props inheritance in React
  • •Building complex hierarchical data models

Interactive Example

// Base Interface
interface Animal {
  name: string;
  age: number;
}

// Inherits 'name' and 'age', adds 'breed'
interface Dog extends Animal {
  breed: string;
}

const myDog: Dog = {
  name: "Rex",
  age: 3,
  breed: "German Shepherd"
};

// Extending Multiple Interfaces
interface CanSwim { swimSpeed: number; }
interface CanFly { flySpeed: number; }

interface Duck extends CanSwim, CanFly {
  quackVolume: number;
}

Interview Questions

basic

  • What keyword is used to inherit from an interface?

intermediate

  • Can an interface extend multiple interfaces at once?

advanced

  • What happens if you extend an interface and redefine a property with a different type?

Flash Cards

Question

Can it extend multiple interfaces?

Click to reveal answer
Answer

Yes! Unlike Classes in JS which can only extend one parent, an interface can extend multiple parents: `interface Square extends Shape, PenStroke { }`.

Question

What happens if you redefine a property type?

Click to reveal answer
Answer

If the new type is a NARROWER version of the old type (e.g., old was `string | number`, new is `string`), it works. If the new type is completely incompatible (old was `number`, new is `string`), TypeScript will throw a compile error.