AI Hints
Home›TypeScript Tutorial›Classes and Contracts
TypeScript · Lesson 47 of 120

Inheritance

Extends.

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

A class can extend another class. It inherits all its properties and methods, and can add or change some. Super calls the parent's version.

Inheritance
From the video: Inheritance
  • extends
  • Inherit everything
  • super

An e-bike class

E bike extends bike. Its constructor calls super, to set up the bike part. It overrides describe, and calls the parent's describe inside. Run it.

app.tstypescript
class Bike {
  constructor(public model: string, public price: number) {}
  describe(): string {
    return `${this.model}, £${this.price}`;
  }
}

class EBike extends Bike {
  constructor(model: string, price: number, public rangeKm: number) {
    super(model, price);
  }
  override describe(): string {
    return `${super.describe()}, ${this.rangeKm} km range`;
  }
}

console.log(new EBike("Volt 7", 2199, 90).describe());
Output
Volt 7, £2199, 90 km range

Use it sparingly

Deep chains of classes get hard to follow. Prefer small interfaces, and combining objects, for most code. Inheritance is best for a clear is a relationship, like an e bike is a bike.

keyvalue
Good forclear is-a
Avoiddeep chains
Preferinterfaces
overridemarks replaced methods

Summary

Extends inherits from a parent class, and super calls the parent's version. Next, abstract classes.

Key takeaways
  • extends
  • super(...)
  • override
Next up: Abstract Classes — must be finished