AI Hints
Home›TypeScript Tutorial›Combining Shapes
TypeScript · Lesson 25 of 120

Extending Interfaces

Build on a shape.

⏱ 2 min read▶ Video at 19:54🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

An electric bike is a bike, with a battery. Instead of repeating every property, an interface can extend another, and add only what's new.

Extending Interfaces
From the video: Extending Interfaces
  • An e-bike is a bike
  • Plus a battery
  • Extend, don't repeat

EBike extends Bike

E bike extends bike, adding the battery range. An e bike has every bike property too. And a function that takes any bike accepts it. Run it.

app.tstypescript
interface Bike {
  model: string;
  price: number;
}

interface EBike extends Bike {
  rangeKm: number;
}

const volt: EBike = { model: "Volt 7", price: 2199, rangeKm: 90 };

function describe(b: Bike) {
  return `${b.model} costs £${b.price}`;
}

console.log(describe(volt), "| range:", volt.rangeKm, "km");
Output
Volt 7 costs £2199 | range: 90 km

Summary

Extends builds a new interface from an old one, so you only add what's new. Next, intersection types.

Key takeaways
  • interface EBike extends Bike
  • Adds properties
  • Still a Bike
Next up: Intersection Types — combine shapes