typescript interface inheritance tutorial

Inheritance is one of the OOPs concepts which provides the facility to create a class (new class) from another class (existing class). Existing class is known as Parent/Super/Base class and new class is know as Child/Sub/Derived class. Child class will acquire the state and behavior of Parent class which can be modified or overridden by child class.

Why inheritance is used?

  • Code re-usability.
  • Run-time polymorphism.

In TypeScript, inheritance can be implemented by Interface or class.

Types of Interface

  • Single Inheritance
  • Multilevel Inheritance
  • Multiple Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance

Note: TypeScript only support Single and Multilevel Inheritance.

Inheritance Using Interface

TypeScript provides the facility of inheritance between interfaces i.e. an interface can inherit other interface. We have to use extends keyword to implement inheritance among interfaces.

Syntax:

ChildInterfaceName extends SuperInterfaceName

Example:

interface Person { 
   age:number;
   name:string;
} 

interface Employee extends Person { 
   empId:string; 
} 

var engineer = {}; 
engineer.age = 30; 
engineer.name = "Jai";
engineer.empId = "EMP024";
console.log("Name:  "+engineer.name);
console.log("Age:  "+engineer.age);
console.log("Emp Id:  "+engineer.empId);

Inheritance Using Class

Syntax:

class subclass extends superclass{
   //subclass code
}

Example:

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

class Engineer extends Employee { 
   display():void { 
      console.log("Name:  "+this.name);
   } 
}
  
var obj = new Engineer("Jai"); 
obj.display();

TypeScript provides the facility to inherit multiple interfaces.

Syntax:

ChildInterfaceName extends SuperInterfaceName1, SuperInterfaceName2,…,SuperInterfaceNamen

Example:

interface IPerson { 
   age:number;
   name:string;
} 

interface IEmployee { 
   empId:string; 
} 

interface Engineer extends IPerson, IEmployee {}

var obj:Engineer = {name:"Asmita", age:32, empId:"EMP023"}; 
console.log("Name:  "+obj.name);
console.log("Age:  "+obj.age);
console.log("Emp Id:  "+obj.empId);