Understanding TypeScript Inheritance

Inheritance in TypeScript

Welcome back! Now that you have a solid understanding of classes and objects, it's time to delve deeper into inheritance. This is a natural progression in our journey into object-oriented programming (OOP) using TypeScript's class-based system—meaning we use classes as blueprints to create and organize objects and their behaviors.

Inheritance in TypeScript allows you to create a new class that reuses the behavior of an existing class. This facilitates code reuse, extends object functionalities, and helps you create easily manageable and understandable programs. Let's dive in!

What We'll Cover

In this lesson, you'll learn how to leverage inheritance in TypeScript. We'll cover:

  1. What Inheritance Is in TypeScript
  2. How to Implement Inheritance Using Classes
  3. Benefits of Using Inheritance

You'll also learn about class hierarchies and how to manage inheritance using constructors and class features.

What Inheritance Is

Inheritance in TypeScript is a mechanism to create a hierarchical class structure, where one class inherits the properties and methods of another. To better understand this, we’ll use an example involving a Person class as the base class and a Student class as the derived class. This will help you see how properties and methods are inherited and extended in TypeScript.

Base Class: Person

Derived Class: Student

Now, we’ll create a Student class that extends the Person class:

// Define the derived class Student, extending from Person
class Student extends Person {
    major: string;

    constructor(name: string, age: number, major: string) {
        super(name, age);
        this.major = major;
    }

    // Method to display major of the student
    displayMajor(): void {
        console.log(`Major: ${this.major}`);
    }
}

In the Student class, we use the extends keyword to inherit from Person. The constructor uses the super function to call the base class constructor, initializing the inherited properties. The Student class adds a new attribute, major, and a displayMajor method specific to its class.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal