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
}- 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
}- 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