How to use Interface with Class in TypeScript ?
Last Updated :
23 Jan, 2025
Improve
In TypeScript, interfaces define the structure that classes must adhere to, ensuring consistent object shapes and facilitating type-checking.
- Interfaces declare properties and methods without implementations, serving as contracts for classes to implement.
- Classes use the implements keyword to adhere to an interface, providing concrete implementations for the declared members.
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
}
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());
- The Shape interface defines a contract with the calculateArea method.
- The Rectangle class implements the Shape interface, providing concrete implementations for the calculateArea method.
- An instance of Rectangle is created with a width of 5 and a height of 10, and the calculateArea method is called to compute the area.
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
}
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()}`);
- The Shape interface declares a calculateArea method, defining a contract for calculating the area of a shape.
- The Color interface includes a color property, specifying that any implementing class should have a color attribute.
- The Circle class implements both Shape and Color interfaces, providing concrete implementations for the calculateArea method and the color property.
Output:
Color: red
Area: 78.53981633974483