How to use Interface with Class in TypeScript ? (original) (raw)

Last Updated : 23 Jan, 2025

In TypeScript, interfaces define the structure that classes must adhere to, ensuring consistent object shapes and facilitating type-checking.

These are the following methods:

1. Interface Implemented by Class

In TypeScript, a class can implement an interface to ensure it adheres to a specific structure defined by the interface.

Syntax:

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

JavaScript `

interface Shape { calculateArea(): number; }

class Rectangle implements Shape { width: number; height: number;

constructor(width: number, height: number) { this.width = width; this.height = height; }

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

const rect = new Rectangle(5, 10); console.log(rect.calculateArea());

`

**Output:

50

2. Multiple Interfaces Implemented by Class

In TypeScript, a class can implement multiple interfaces, allowing it to adhere to multiple contracts and ensuring it provides implementations for all the specified members.

Syntax:

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

JavaScript ``

interface Shape { calculateArea(): number; }

interface Color { color: string; }

class Circle implements Shape, Color { radius: number; color: string;

constructor(radius: number, color: string) { this.radius = radius; this.color = color; }

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

const circle = new Circle(5, 'red'); console.log(Color: ${circle.color}); console.log(Area: ${circle.calculateArea()});

``

**Output:

Color: red
Area: 78.53981633974483