Open In App

How to Extend an Interface from a class in TypeScript ?

In this article, we will try to understand how we to extend an interface from a class in TypeScript with the help of certain coding examples. Let us first quickly understand how we can create a class as well as an interface in TypeScript using the following mentioned syntaxes:

Syntax: 



This is the syntax for creating a class. We may use the below syntax for creating a class in TypeScript:

class class_name {
    ...
}

This is the syntax for creating an interface. We may use the below syntax for creating an interface in TypeScript:



interface interface_name {
    ...
}

Now that we have understood the basic syntaxes for creating a class and an interface, let us understand those syntaxes along with the main objective of how we could extend an interface from a class with the help of the following coding examples:

Example 1:




// Parent class creation
class Person {
    public name: string;
}
  
// Interface extended from the above class
interface Details extends Person {
    details(): void;
}
  
// Using the above illustrated interface and class together
class Person_Details extends Person implements Details {
    details(): void {
        this.name = "GeeksforGeeks";
        console.log(this.name);
    }
}
  
let object = new Person_Details();
object.details();

Output:

GeeksforGeeks

Example 2:




// Parent class declaration
class Student {
    public id: number;
    public name: string;
}
  
// Creating multiple interfaces which 
// will extend the above class
interface Student_1 extends Student {
    student1_details(): void;
}
  
interface Student_2 extends Student {
    student2_details(): void;
}
  
// Creating a class which will extend
// the above interfaces 
class Student_Details extends Student implements Student_1, Student_2 {
    student1_details(): void {
        this.name = "Apple";
        this.id = 1;
        console.log(this.id + " - " + this.name);
    }
  
    student2_details(): void {
        this.name = "Banana";
        this.id = 2;
        console.log(this.id + " - " + this.name);
    }
}
  
let student_object = new Student_Details();
student_object.student1_details();
student_object.student2_details();

Output:

1 - Apple
2 - Banana

Article Tags :