Open In App

How to implement Inheritance in Typescript ?

Last Updated : 14 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Inheritance is a major pillar of object-oriented programming languages and inheritance is used to create a new class from the existing one. The newly created class is known as the Derived class and the class from which the derived class inherited is known as the Base class. An inherited derived class acquires the properties and behaviors of the base class. TypeScript supports single inheritance and multilevel inheritance. We can not implement hybrid and multiple inheritances using TypeScript. The inheritance uses class-based inheritance and it can be implemented using extends keywords in typescript. In this article, we will see how inheritance is implemented in TypeScript.

Syntax:

class baseClassName {
}
class derivedClassName extends baseClassName {
}

Single Inheritance in TypeScript: In single inheritance, the properties and behaviour of the base class can be inherited into at most one derived class. It used to add new functionality to the already implemented class.

Example: In this example, we are creating a Person as a base class and using single inheritance implementing Teacher as a Derived class. 

 

Javascript




// Base class
class Person {
  Name: string;
  constructor(name: string) {
    this.Name = name;
  }
}
// Deriving Teacher class
class Teacher extends Person {
  Payment: number;
  constructor(name: string, payment: number) {
    super(name);
    this.Payment = payment;
  }
  display(): void {
    console.log("Teacher's Name: " + this.Name);
    console.log("Teacher's Payment " + this.Payment);
  }
}
// Create Object
let obj = new Teacher("GeeksforGeeks", 8500000);
obj.display();


Output:

Teacher's Name: GeeksforGeeks 
Teacher's Payment 8500000

2.Multilevel Inheritance:

In multilevel inheritance, the derived class acts as the base class for another derived class. The newly created derived class acquires the properties and behavior of other base classes.

Example: In this example, we are creating a Vehicle as a base class and a Car as a subclass which deriving the new class called carModel and the class carModel acquires all features of the Vehicle as well as Car class.

Javascript




// Base class
class Vehicle {
  Type(): void {
    console.log("Car");
  }
}
  
// Inherites from Vehicle
class Car extends Vehicle {
  Brand(): void {
    console.log("ABC");
  }
}
  
// Inherites all properties of 
// Vehicle and Car class
class carModel extends Car {
  Model(): void {
    console.log("ABC2021");
  }
}
  
// Object creation
let obj = new carModel();
obj.Type();
obj.Brand();
obj.Model();


Output:

Car  
ABC
ABC2021


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads