How Does Inheritance Work in TypeScript?

Learn How Does Inheritance Work in TypeScript? with practical examples, explanations, best practices, and real-world coding techniques.

Introduction to Inheritance in TypeScript

Inheritance is an object-oriented programming concept that allows one class to reuse and extend the properties and methods of another class. Instead of implementing the same behavior repeatedly, you can define shared functionality in a base class and create specialized classes that build upon it.

For example, an application might contain Employee, Developer, and Manager classes. All employees have common properties such as a name and employee identifier, but developers and managers may have additional responsibilities. A base class can define the common behavior, while derived classes introduce specialized functionality.

TypeScript supports class inheritance through the extends keyword. It also provides static type checking for inherited properties, method parameters, return types, access modifiers, and overridden methods.

Inheritance is useful when classes have a meaningful relationship and share behavior that should remain consistent. When objects only need to reuse unrelated functionality, composition can often provide a simpler and more flexible design.

1. Understanding Base Classes and Derived Classes

A base class defines properties and methods that another class can inherit. The class that extends the base class is called a derived class or subclass.

Consider a basic example using an Animal class and a Dog class.

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

  speak(): string {
    return this.name + " makes a sound.";
  }
}

class Dog extends Animal {
  bark(): string {
    return this.name + " barks.";
  }
}

const dog = new Dog("Buddy");

console.log(dog.speak());
console.log(dog.bark());

Animal is the base class, and Dog is the derived class. The Dog class inherits the name property and speak method from Animal without declaring them again.

Dog also defines its own bark method. A Dog instance can therefore access both the inherited behavior and its additional functionality.

The extends keyword establishes the inheritance relationship. TypeScript checks that the derived class follows the rules associated with the base class and its inherited members.

2. Using the extends Keyword

The extends keyword specifies which class a new class inherits from. A derived class receives accessible instance members and can add new properties, introduce additional methods, or replace inherited method implementations when permitted.

class Employee {
  constructor(
    public name: string,
    public department: string
  ) {}

  getDetails(): string {
    return this.name + " works in " + this.department;
  }
}

class Developer extends Employee {
  constructor(
    name: string,
    department: string,
    public programmingLanguage: string
  ) {
    super(name, department);
  }

  writeCode(): string {
    return this.name + " writes " + this.programmingLanguage;
  }
}

const developer = new Developer(
  "Abhinash",
  "Engineering",
  "TypeScript"
);

console.log(developer.getDetails());
console.log(developer.writeCode());

Developer inherits the name and department properties and the getDetails method from Employee. It adds programmingLanguage and introduces writeCode.

This design keeps shared employee information in one place while allowing each specialized class to represent its own behavior.

TypeScript uses single class inheritance: a class can extend one class directly. However, classes can implement multiple interfaces when they need to satisfy several independent contracts.

3. Understanding the super() Constructor Call

When a derived class declares its own constructor, it must call super() before accessing this. This calls the base class constructor and initializes the inherited portion of the object.

class Person {
  constructor(
    public name: string,
    public age: number
  ) {}
}

class Student extends Person {
  constructor(
    name: string,
    age: number,
    public course: string
  ) {
    super(name, age);
  }

  getSummary(): string {
    return this.name + " studies " + this.course;
  }
}

const student = new Student(
  "Abhinash",
  27,
  "TypeScript"
);

console.log(student.getSummary());

The Person constructor accepts a name and age. Student adds a course property and forwards the inherited values to the base constructor using super(name, age).

Because Student declares a constructor, the base constructor must be invoked explicitly. The derived constructor can then initialize its own parameter properties.

If a derived class does not declare a constructor, it can use the inherited construction behavior, subject to the base class's constructor requirements. When defining an explicit derived constructor, make sure the arguments passed to super match the intended base initialization.

4. Adding Properties and Methods in Derived Classes

A derived class can introduce new properties and methods without changing the base class. This allows related classes to share essential functionality while supporting distinct responsibilities.

class Vehicle {
  constructor(
    public brand: string,
    public speed: number
  ) {}

  accelerate(amount: number): void {
    this.speed += amount;
  }

  getSpeed(): number {
    return this.speed;
  }
}

class Car extends Vehicle {
  constructor(
    brand: string,
    speed: number,
    public numberOfDoors: number
  ) {
    super(brand, speed);
  }

  openTrunk(): string {
    return "The trunk of the " + this.brand + " is open.";
  }
}

const car = new Car("Toyota", 60, 4);

car.accelerate(20);

console.log(car.getSpeed());
console.log(car.openTrunk());
console.log(car.numberOfDoors);

Vehicle provides the shared brand and speed properties and the accelerate and getSpeed methods. Car adds a numberOfDoors property and an openTrunk method.

The inherited methods operate on the same Car instance. After accelerate updates the speed, getSpeed returns the updated value.

Derived classes should add behavior that is genuinely specific to their role. If the base class accumulates too many unrelated responsibilities, splitting those responsibilities into separate classes or services may improve maintainability.

5. Overriding Methods in TypeScript

Method overriding occurs when a derived class provides its own implementation of a method inherited from the base class. The derived implementation can specialize the behavior while keeping the same method contract.

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

  speak(): string {
    return this.name + " makes a sound.";
  }
}

class Dog extends Animal {
  override speak(): string {
    return this.name + " barks.";
  }
}

class Cat extends Animal {
  override speak(): string {
    return this.name + " meows.";
  }
}

const dog = new Dog("Buddy");
const cat = new Cat("Milo");

console.log(dog.speak());
console.log(cat.speak());

Both Dog and Cat replace the inherited speak implementation with behavior appropriate to their own classes.

The override keyword explicitly communicates that a method is intended to replace an inherited member. It also helps TypeScript catch mistakes, such as misspelling the name of the method being overridden.

The override keyword was introduced in TypeScript 4.3. In projects using a compatible TypeScript version, consider enabling noImplicitOverride so that overriding inherited members requires explicit annotation.

An overriding method should remain compatible with the base class's contract. Code that works with an Animal should be able to use a Dog or Cat wherever the Animal interface is expected without breaking the intended behavior.

6. Understanding the super Keyword in Methods

The super keyword can also be used inside a derived class method to call an implementation from the base class. This is helpful when you want to extend inherited behavior instead of replacing it completely.

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

  getDescription(): string {
    return "Employee: " + this.name;
  }
}

class Manager extends Employee {
  override getDescription(): string {
    const baseDescription = super.getDescription();

    return baseDescription + " (Manager)";
  }
}

const manager = new Manager("Abhinash");

console.log(manager.getDescription());

The base class returns a general employee description. Manager invokes that implementation through super.getDescription() and appends its own information.

This approach avoids copying the base implementation into the derived class. If the base description changes later, the manager can continue using the updated implementation.

Use super when extending behavior is more appropriate than duplicating logic. If the subclass changes the meaning or requirements of the base operation, reconsider whether the inheritance relationship is appropriate.

7. Understanding protected Members in Inheritance

The protected modifier allows a member to be accessed within its declaring class and its subclasses. It is useful when derived classes need to reuse internal state or helper methods without exposing them to all callers.

class Employee {
  constructor(
    public name: string,
    protected department: string
  ) {}

  protected getWorkplace(): string {
    return this.department;
  }
}

class Developer extends Employee {
  describe(): string {
    return this.name + " works in " + this.getWorkplace();
  }
}

const developer = new Developer(
  "Abhinash",
  "Engineering"
);

console.log(developer.describe());

// Compilation error:
// console.log(developer.department);

// Compilation error:
// developer.getWorkplace();

Developer can access the inherited protected department property and getWorkplace method from within its own implementation. External code cannot access them directly through the developer instance under TypeScript's access checks.

By contrast, a private member declared in Employee cannot be accessed directly from Developer. Protected members should be used deliberately because subclasses become dependent on the base class's internal design.

8. Understanding private Members in Inheritance

A member declared with TypeScript's traditional private modifier is accessible only within the declaring class's implementation through normal TypeScript member access. A subclass inherits the behavior of its base class but cannot directly access its private properties or methods.

class Employee {
  private salary: number;

  constructor(
    public name: string,
    salary: number
  ) {
    this.salary = salary;
  }

  getSalary(): number {
    return this.salary;
  }
}

class Developer extends Employee {
  describe(): string {
    return this.name + " has a salary of " + this.getSalary();
  }
}

const developer = new Developer("Abhinash", 60000);

console.log(developer.describe());

// Compilation error inside Developer:
// return this.salary;

The salary field remains the responsibility of Employee. Developer can call the inherited public getSalary method, but it cannot refer to salary directly.

This design permits a base class to control how internal state is accessed while still providing deliberate operations for subclasses and external callers.

Traditional TypeScript private modifiers are enforced by the type checker rather than providing the same runtime protection as JavaScript #privateField syntax. Neither kind of class member visibility should be treated as a substitute for API authorization or broader application security.

9. Understanding Polymorphism

Polymorphism allows related objects to be used through a shared base type while providing different implementations of the same operation. In TypeScript, method overriding and base-class references are common ways to demonstrate this concept.

class Shape {
  getArea(): number {
    return 0;
  }
}

class Rectangle extends Shape {
  constructor(
    public width: number,
    public height: number
  ) {
    super();
  }

  override getArea(): number {
    return this.width * this.height;
  }
}

class Circle extends Shape {
  constructor(public radius: number) {
    super();
  }

  override getArea(): number {
    return Math.PI * this.radius * this.radius;
  }
}

function printArea(shape: Shape): void {
  console.log(shape.getArea());
}

printArea(new Rectangle(10, 5));
printArea(new Circle(3));

The printArea function accepts a Shape reference. It can work with a Rectangle or Circle because both classes extend Shape and provide an appropriate getArea implementation.

When getArea is called, JavaScript invokes the implementation associated with the actual object. A rectangle calculates its area using width and height, while a circle calculates its area using its radius.

Polymorphism makes shared code easier to extend. A new shape can provide its own implementation without requiring changes to printArea, provided it satisfies the expected contract.

10. Understanding Inheritance and Constructors

When a derived class is instantiated, JavaScript initializes its base class portion through the constructor chain. If the derived class defines a constructor, it must call super before accessing this.

class Person {
  constructor(
    public name: string,
    public age: number
  ) {
    console.log("Person initialized");
  }
}

class Student extends Person {
  constructor(
    name: string,
    age: number,
    public course: string
  ) {
    super(name, age);

    console.log("Student initialized");
  }
}

const student = new Student(
  "Abhinash",
  27,
  "TypeScript"
);

The Person constructor initializes the inherited name and age properties. After super completes, the Student constructor continues with its own initialization.

Constructor execution order matters when base classes perform initialization or validate input. Keep base constructors focused, and avoid relying on derived-class state before that state has been initialized.

Remember that constructors themselves are not inherited as ordinary methods. A derived class can use the base class's construction behavior when it does not define its own constructor, but it must define an appropriate constructor when additional setup or parameter handling is required.

11. Extending Built-in Classes

TypeScript also supports extending built-in JavaScript classes when the runtime and compilation target support the required behavior. For example, a custom error class can extend Error to represent application-specific failures.

class ValidationError extends Error {
  constructor(message: string) {
    super(message);

    this.name = "ValidationError";
  }
}

function validateUsername(username: string): void {
  if (username.trim().length < 3) {
    throw new ValidationError(
      "Username must contain at least three characters."
    );
  }
}

try {
  validateUsername("ab");
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(error.name);
    console.log(error.message);
  } else {
    throw error;
  }
}

ValidationError extends the built-in Error class and supplies a custom name. The instance still provides inherited properties such as message.

The instanceof operator checks whether the caught object is an instance of ValidationError or its relevant prototype chain. TypeScript can narrow the error to ValidationError inside the corresponding branch.

Custom error classes can help applications distinguish validation failures from other errors. When extending built-in classes, ensure the project's JavaScript target and runtime configuration correctly support native class inheritance.

12. Inheritance vs. Composition

Inheritance is useful when one class represents a specialized form of another class. However, code reuse alone is not always sufficient reason to create an inheritance relationship.

Consider an application that needs to let several different objects send notifications. Instead of making every notification-related class inherit from a large base class, you could define a notification service and pass it to the objects that need it.

class EmailNotificationService {
  send(message: string): void {
    console.log("Email sent: " + message);
  }
}

class UserService {
  constructor(
    private notifications: EmailNotificationService
  ) {}

  registerUser(name: string): void {
    console.log("Registered: " + name);

    this.notifications.send(
      "Welcome, " + name
    );
  }
}

const notifications = new EmailNotificationService();
const users = new UserService(notifications);

users.registerUser("Abhinash");

UserService uses an EmailNotificationService rather than inheriting from it. This is an example of composition: one object contains or receives another object to perform a task.

Composition makes it easier to replace the notification implementation or share it across unrelated classes. In larger applications, an interface can define the notification contract so the implementation can be substituted more easily.

Choose inheritance when there is a meaningful subtype relationship and subclasses can honor the base class's contract. Choose composition when an object simply needs another object's capabilities.

13. Common Mistakes to Avoid

  • Forgetting super(): an explicit derived constructor must call super before accessing this.
  • Accessing private base members: inherited behavior may use a base class's private fields, but derived classes cannot directly access those fields through normal TypeScript member access.
  • Incorrectly overriding methods: ensure an overriding method remains compatible with the base method's signature and intended behavior. Use the override keyword when supported.
  • Exposing too many protected members: excessive protected state creates tight coupling between base classes and their subclasses.
  • Creating deep inheritance hierarchies: long chains make behavior harder to trace and changes more difficult to maintain.
  • Using inheritance only for convenience: sharing one or two methods does not necessarily mean that one class should extend another.
  • Ignoring polymorphic behavior: code that accepts a base type should work correctly with every supported subtype.
  • Assuming compile-time modifiers provide runtime security: TypeScript access modifiers do not replace authentication, authorization, or runtime data validation.

14. Best Practices for Inheritance

  • Use inheritance to represent a genuine specialization relationship between classes.
  • Keep base classes focused on stable behavior shared by their subclasses.
  • Use super() consistently to initialize inherited state and reuse base method behavior.
  • Mark overridden methods with override when supported by the project's TypeScript version.
  • Expose only the members subclasses need; keep implementation details private when possible.
  • Use polymorphism to write reusable code that works with several compatible subclasses.
  • Prefer composition when a class needs another object's capabilities without representing a subtype of that object.
  • Avoid deep inheritance hierarchies and duplicated initialization logic.
  • Test both inherited and overridden behavior to ensure each subclass satisfies the base class's contract.

Conclusion

Inheritance in TypeScript allows classes to reuse and extend existing functionality through the extends keyword. Base classes define shared behavior, derived classes add specialized capabilities, and super() initializes inherited state or invokes base implementations.

Method overriding and polymorphism allow different subclasses to provide their own behavior while remaining usable through a common base type. Access modifiers help manage which members are available to subclasses and external callers.

By designing focused base classes, preserving method contracts, and choosing composition when inheritance is not a natural fit, you can create object-oriented TypeScript code that is reusable, extensible, and easier to maintain.

Code Examples

Create a Base Class and Derived Class

typescript
class Animal {
  constructor(public name: string) {}

  speak(): string {
    return this.name + " makes a sound.";
  }
}

class Dog extends Animal {
  bark(): string {
    return this.name + " barks.";
  }
}

const dog = new Dog("Buddy");

console.log(dog.speak());
console.log(dog.bark());
    

Initialize Inherited Properties with super()

typescript
class Employee {
  constructor(
    public name: string,
    public department: string
  ) {}
}

class Developer extends Employee {
  constructor(
    name: string,
    department: string,
    public programmingLanguage: string
  ) {
    super(name, department);
  }
}

const developer = new Developer(
  "Abhinash",
  "Engineering",
  "TypeScript"
);

console.log(developer.name);
console.log(developer.department);
console.log(developer.programmingLanguage);
    

Override an Inherited Method

typescript
class Animal {
  constructor(public name: string) {}

  speak(): string {
    return this.name + " makes a sound.";
  }
}

class Cat extends Animal {
  override speak(): string {
    return this.name + " meows.";
  }
}

const cat = new Cat("Milo");

console.log(cat.speak());
    

Use super Inside an Overridden Method

typescript
class Employee {
  constructor(public name: string) {}

  getDescription(): string {
    return "Employee: " + this.name;
  }
}

class Manager extends Employee {
  override getDescription(): string {
    return super.getDescription() + " (Manager)";
  }
}

const manager = new Manager("Abhinash");

console.log(manager.getDescription());
    

Demonstrate Polymorphism

typescript
class Shape {
  getArea(): number {
    return 0;
  }
}

class Rectangle extends Shape {
  constructor(
    public width: number,
    public height: number
  ) {
    super();
  }

  override getArea(): number {
    return this.width * this.height;
  }
}

class Circle extends Shape {
  constructor(public radius: number) {
    super();
  }

  override getArea(): number {
    return Math.PI * this.radius ** 2;
  }
}

function printArea(shape: Shape): void {
  console.log(shape.getArea());
}

printArea(new Rectangle(10, 5));
printArea(new Circle(3));
    

Use Composition Instead of Inheritance

typescript
class NotificationService {
  send(message: string): void {
    console.log("Notification: " + message);
  }
}

class UserService {
  constructor(
    private notifications: NotificationService
  ) {}

  registerUser(name: string): void {
    console.log("Registered: " + name);
    this.notifications.send("Welcome, " + name);
  }
}

const notifications = new NotificationService();
const users = new UserService(notifications);

users.registerUser("Abhinash");
    

Pro Tip

Use inheritance when a derived class is genuinely a specialized form of its base class, and ensure every subclass honors the base class contract. Call super() before accessing this in derived constructors, use override for intentional method replacements, and prefer composition when you only need to reuse another object's capabilities.

More TypeScript lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.