5️⃣ 🧩 TypeScript — Interfaces & Classes (OOP)
Estimated reading: 4 minutes 36 views

🧬 TypeScript — Inheritance: Reuse and Extend Class Functionality

🧲 Introduction – What Is Inheritance in TypeScript?

Inheritance in TypeScript is a key object-oriented programming feature that allows one class (the child or subclass) to extend another class (the parent or superclass). This means the subclass inherits all public and protected properties and methods of the parent class and can override or enhance them as needed.

🎯 In this guide, you’ll learn:

  • How to implement inheritance in TypeScript using extends
  • The use of super() in subclass constructors
  • Overriding methods and accessing protected members
  • Inheriting with access modifiers
  • Real-world examples and best practices

🏗️ Basic Inheritance Syntax

Use the extends keyword to create a child class that inherits from a parent class.

✅ Example:

class Animal {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  move(): void {
    console.log(`${this.name} is moving`);
  }
}

class Dog extends Animal {
  bark(): void {
    console.log(`${this.name} says Woof!`);
  }
}

const pet = new Dog("Buddy");
pet.move(); // Buddy is moving
pet.bark(); // Buddy says Woof!

Explanation:

  • Dog inherits the name property and move() method from Animal.
  • It also has its own method bark().

🚀 Using super() in Subclass Constructors

When a subclass has its own constructor(), it must call super() to initialize the parent class.

class Person {
  constructor(public name: string) {}
}

class Employee extends Person {
  constructor(name: string, public employeeId: number) {
    super(name); // Call parent constructor
  }
}

Explanation:

  • super(name) calls the Person constructor.
  • Without super(), TypeScript throws a compile-time error.

🔄 Method Overriding

A subclass can override a method from its superclass with a custom implementation.

class Vehicle {
  start() {
    console.log("Starting vehicle...");
  }
}

class Car extends Vehicle {
  start() {
    console.log("Starting car engine...");
  }
}

const car = new Car();
car.start(); // Output: Starting car engine...

📌 Use super.methodName() if you want to include the parent method’s behavior too.


🛡️ Access Modifiers and Inheritance

🔹 public: Accessible anywhere (default)

class Base {
  public greeting = "Hello";
}

class Derived extends Base {
  sayHi() {
    console.log(this.greeting); // ✅ Accessible
  }
}

🔹 protected: Accessible within class and subclasses only

class User {
  protected username = "admin";
}

class Admin extends User {
  showUsername() {
    console.log(this.username); // ✅ Accessible
  }
}

// const user = new User();
// console.log(user.username); // ❌ Error: Protected

🔹 private: Not accessible outside the class

class BankAccount {
  private balance = 1000;

  getBalance() {
    return this.balance;
  }
}

class SavingsAccount extends BankAccount {
  // console.log(this.balance); // ❌ Error: Private property
}

🧱 Multilevel and Hierarchical Inheritance

✅ Multilevel Inheritance:

class A {
  greet() {
    console.log("Hello from A");
  }
}

class B extends A {
  welcome() {
    console.log("Welcome from B");
  }
}

class C extends B {
  hello() {
    console.log("Hi from C");
  }
}

const obj = new C();
obj.greet();  // A
obj.welcome(); // B
obj.hello();   // C

📚 Real-World Use Cases

  • 🔐 User roles: Base User class, extended by Admin, Customer, Guest
  • 🚗 Vehicle types: Base Vehicle class, extended by Car, Truck, Bike
  • 🧾 Form validations: Base FormField class, extended by TextField, Dropdown, Checkbox
  • 🎮 Game entities: Base Entity class, extended by Player, Enemy, NPC

⚠️ Common Mistakes & How to Avoid Them

❌ Mistake✅ Solution
Forgetting to call super() in subclassAlways call super() in a subclass constructor
Accessing private members from child classUse protected if you want to allow subclass access
Overriding methods without preserving logicUse super.method() to call parent method if needed
Overusing inheritanceConsider composition over inheritance when possible

💡 Best Practices for Inheritance in TypeScript

  • ✅ Keep parent classes small and focused
  • ✅ Use protected to expose members to child classes
  • ✅ Prefer method overriding over property redefinition
  • ✅ Avoid deep inheritance hierarchies (2–3 levels max)
  • ✅ Consider abstract classes for reusable base logic

📌 Summary – Recap & Next Steps

Inheritance in TypeScript lets you reuse logic, enforce consistency, and organize code hierarchically. It’s a foundational concept in object-oriented TypeScript development, ideal for building scalable class architectures.

🔍 Key Takeaways:

  • Use extends to create a child class that inherits from a parent
  • Call super() to initialize inherited properties
  • Use protected to safely expose members to subclasses
  • Override methods for specialized behavior
  • Avoid overly complex inheritance trees

⚙️ Real-world relevance: Inheritance is used in UI component trees, game engines, object models, validation systems, and stateful services.


❓ FAQs – Inheritance in TypeScript

❓ Can a class extend multiple classes in TypeScript?
❌ No. TypeScript supports single inheritance only, but multiple interfaces can be implemented.

❓ Can I call a parent method from a child class?
✅ Yes. Use super.methodName() to call the parent’s method.

❓ Can I override constructors in TypeScript?
✅ Yes, but you must call super() before accessing this.

❓ Should I use inheritance or composition?
📌 Prefer composition when classes become overly complex or deeply nested.

❓ Are access modifiers required for inheritance to work?
No, but using protected improves clarity and control over access in subclasses.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

TypeScript — Inheritance

Or Copy Link

CONTENTS
Scroll to Top