Interface Implemented by Class

In this approach, an interface named Shape is defined with a method calFn() that calculates a shape’s area. The Rectangle class implements the Shape interface by providing its implementation of calFn(), the calculation of a rectangle’s area when an instance of Rectangle is created and calFn() is called on that instance.

Syntax:

class ClassName implements InterfaceName {
   // Class properties and methods
}

Example: The below example demonstrates the Interface Implemented by the Class.

JavaScript
interface Shape {
    calFn(): number;
}

class Rectangle implements Shape {
    constructor(private width: number,
        private height: number) { }

    calFn(): number {
        return this.width * this.height;
    }
}

const obj = new Rectangle(5, 10);
console.log('Area of rectangle:', 
    obj.calFn());

Output:

Area of rectangle: 50

How to use Interface with Class in TypeScript ?

Interface and Class in TypeScript are fundamental concepts for defining object structures and behavior, where interfaces provide a blueprint for properties and methods, and classes implement these interfaces to create objects with specific functionality and structure.

These are the following methods:

Table of Content

  • Interface Implemented by Class
  • Multiple Interfaced Implemented by Class

Similar Reads

Interface Implemented by Class

In this approach, an interface named Shape is defined with a method calFn() that calculates a shape’s area. The Rectangle class implements the Shape interface by providing its implementation of calFn(), the calculation of a rectangle’s area when an instance of Rectangle is created and calFn() is called on that instance....

Multiple Interfaces Implemented by Class

In this approach, a class Circle implements both the Shape and Color interfaces, allowing it to define methods for calculating area (calFn()) and specifying a color. When an instance of Circle is created, it can access methods from both interfaces, such as retrieving the color and calculating the area of the circle....

Contact Us