Understanding Inheritance in TypeScript

Introduction to Inheritance

Welcome back to our exploration of Object-Oriented Programming (OOP) in TypeScript. This unit's topic is Inheritance, a feature that can significantly enhance code reusability and efficiency.

Inheritance: First Example

Programming, especially OOP, often mirrors concepts found in the real world. Inheritance is one such trait - Child classes inherit characteristics from their Parent classes, akin to genetics in biology.

Here is a concrete TypeScript demonstration of a Child class inheriting from a Parent class:

TypeScript
// Parent class
class Parent {
    name: string; // name property

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

    greet(): void {
        console.log(`Hello, my name is ${this.name}`); // greet method
    }
}

// 'Child' class extending 'Parent'
class Child extends Parent {
    age: number; // age property

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

    info(): void {
        console.log(`I am ${this.age} years old.`); // info method
    }
}

const child = new Child('Alice', 10);
child.greet(); // prints: Hello, my name is Alice
child.info(); // prints: I am 10 years old.

In this instance, the Child class inherits from the Parent class, thereby sharing the greet() method. This is inheritance in action!

The 'extends' Keyword

We introduce the keyword extends for implementing inheritance. It's a potent keyword that allows a new class to inherit properties and methods from an existing class. In short, a Child class extends from a Parent class.

For example, a Car extends a Vehicle. While both have the potential for movement, a Car has additional specific attributes — such as the number of wheels.

TypeScript
// Vehicle class
class Vehicle {
    name: string; // name property
    speed: number; // speed property

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

    move(): void {
        console.log(`${this.name} moves at ${this.speed} mph.`); // move method 
    }
}

// 'Car' class extending 'Vehicle'
class Car extends Vehicle {
    wheels: number; // new wheels property

    constructor(name: string, speed: number, wheels: number) {
        super(name, speed); // call to parent constructor
        this.wheels = wheels;
    }

    specs(): void {
        console.log(`I am a ${this.name} and I have ${this.wheels} wheels.`); // specs method
    }
}

const myCar = new Car('Toyota', 120, 4);
myCar.move(); // prints: Toyota moves at 120 mph
myCar.specs(); // prints: I am a Toyota and I have 4 wheels.

In this demonstration, the Car class extends the Vehicle class, adopting the move() method.

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