← Back to TypeScript Course | Chapter 6: Classes | Lesson 6 of 9

Inheritance

Inheritance allows one class to reuse properties and methods from another class. In TypeScript, the extends keyword creates a relationship where a derived class can add or customize behavior from a base class.

Basic Inheritance

A derived class uses extends to inherit from a base class, and the derived class automatically gains access to the base class's public and protected members without having to redeclare them.

Example: Basic Inheritance

typescript
class Animal {
  eat() { console.log("Eating"); }
}
class Dog extends Animal {
  bark() { console.log("Barking"); }
}
const dog = new Dog();
dog.eat();
dog.bark();

Inherited Properties

A derived class can use properties declared by its base class according to their visibility — public and protected members are inherited and usable, while private members remain locked to the base class alone.

Example: Inherited Properties

typescript
class Animal {
  public name: string = "Animal";
  protected sound: string = "...";
}
class Dog extends Animal {
  describe() {
    console.log(this.name, this.sound);
  }
}
new Dog().describe();

Calling the Base Constructor

When a derived class defines its own constructor, it must call the base class constructor with super(...) before it can access this, ensuring the inherited part of the object is fully initialized first.

Example: Calling the Base Constructor

typescript
class Animal {
  constructor(public name: string) {}
}
class Dog extends Animal {
  constructor(name: string, public breed: string) {
    super(name);
  }
}
const d = new Dog("Rex", "Labrador");
console.log(d.name, d.breed);

Method Overriding

A derived class can provide its own implementation of an inherited method; the override keyword documents this intent explicitly and lets the compiler catch mistakes like misspelling the method name.

Example: Method Overriding

typescript
class Animal {
  speak() { console.log("..."); }
}
class Dog extends Animal {
  override speak() { console.log("Woof"); }
}
new Dog().speak();

Benefits of Inheritance

Inheritance reduces repeated code and models real relationships between related types, such as a Manager class extending Employee, but it should be reached for only when a genuine is-a relationship exists between the classes.

Example: Benefits of Inheritance

typescript
class Employee {
  constructor(public name: string) {}
}
class Manager extends Employee {
  manageTeam() { console.log(`${this.name} manages the team`); }
}
new Manager("Riya").manageTeam();

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.