Inheritance in TypeScript - Extending Classes


Introduction

Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows you to create a new class by inheriting properties and methods from an existing class. TypeScript supports single inheritance and provides a mechanism to extend classes. In this guide, we'll explore how to use inheritance in TypeScript to create derived classes that inherit from base classes.


Defining a Base Class

A base class, also known as a superclass, serves as the template for creating derived classes. It defines properties and methods that are shared by the derived classes.


Example:

class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound() {
console.log(this.name + " makes a sound.");
}
}

Extending a Class

To create a derived class, you use the extends keyword, which indicates that the new class should inherit from an existing class (base class).


Example:

class Dog extends Animal {
breed: string;
constructor(name: string, breed: string) {
super(name);
this.breed = breed;
}
makeSound() {
console.log(this.name + " barks loudly.");
}
}
const myDog = new Dog("Fido", "Golden Retriever");

Calling Superclass Constructor

In the derived class constructor, you can call the constructor of the superclass using super() to initialize properties defined in the base class.


Method Overriding

Derived classes can override methods from the base class. This means that they provide their own implementation of a method, which is used when the method is called on an object of the derived class.


Example:

class Cat extends Animal {
constructor(name: string) {
super(name);
}
makeSound() {
console.log(this.name + " purrs softly.");
}
}
const myCat = new Cat("Whiskers");

Conclusion

Inheritance is a powerful mechanism in TypeScript that allows you to create new classes based on existing ones, promoting code reuse and maintaining a hierarchical structure. By extending classes and using method overriding, you can create complex class hierarchies to model real-world entities and behaviors in your applications.