In TypeScript, implementing inheritance offers a concise and intuitive approach, primarily achieved by using the extends keyword. Inheritance enables us to create a class (subclass) that inherits properties and methods from another class (superclass), while also adding or overriding methods and properties. This is a core concept in object-oriented programming, facilitating code reuse and organization.
Example
Assume we have a base class called Vehicle with basic properties and methods, and we want to create a Car class that inherits from Vehicle while introducing specific properties and methods.
typescript// Define the superclass class Vehicle { // Properties public brand: string; public model: string; // Constructor constructor(brand: string, model: string) { this.brand = brand; this.model = model; } // Method displayInfo(): void { console.log(`This vehicle is a ${this.brand} ${this.model}`); } } // Define the subclass class Car extends Vehicle { // New property public doors: number; // Constructor constructor(brand: string, model: string, doors: number) { super(brand, model); // Call the superclass constructor this.doors = doors; } // Override method displayInfo(): void { super.displayInfo(); // Call the superclass method console.log(`It has ${this.doors} doors.`); } } // Create an instance of Car let myCar = new Car("Toyota", "Corolla", 4); myCar.displayInfo(); // Output: This vehicle is a Toyota Corolla // It has 4 doors.
Explanation
-
Class Definition: We first define a
Vehicleclass with basic properties such asbrandandmodel, and a methoddisplayInfo(). -
Inheritance: The
Carclass inherits fromVehicleusing theextendskeyword. This means theCarclass inherits all properties and methods from theVehicleclass. -
super Keyword: In the
Carclass constructor, we callsuper()to invoke theVehicleclass constructor, which is necessary for initializing inherited properties. Within thedisplayInfo()method, we callsuper.displayInfo()to invoke the superclass method and then add additional logic. -
Overriding Methods: In the subclass, we can override methods by defining methods with the same name as in the superclass. In this example, the
Carclass overrides thedisplayInfo()method.
This example demonstrates how to use inheritance in TypeScript to create new classes with additional functionality while maintaining concise and maintainable code structure. Inheritance is a key mechanism for achieving code reuse and logical layering.