Open In App

How to use Interface with Class in TypeScript ?

Last Updated : 02 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

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

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.

Syntax:

class ClassName implements Interface1, Interface2, ... {
   // Class properties and methods
 }

Example: The below example demonstrates the Multiple Interfaces Implemented by Class.

JavaScript
interface Color {
    color: string;
}
interface Shape {
    calFn(): number;
}
class Circle implements Shape, Color {
    constructor(public radius: number, 
        public color: string) { }

    calFn(): number {
        return Math.PI * this.radius ** 2;
    }
}

const obj = new Circle(5, 'red');
console.log('Color of circle:', obj.color);
console.log('Area of circle:', obj.calFn());

Output:

Color of circle: red
Area of circle: 78.53981633974483

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads