In TypeScript, interfaces are named collections of method signatures, similar to the concept in other languages. They define a contract that classes can implement.
In this example, we define a Geometry interface with area() and perim() methods. We then implement this interface for Rect and Circle classes.
The measure function demonstrates how interfaces can be used for polymorphism. It accepts any object that implements the Geometry interface, allowing us to use the same function for different shapes.
In the main function, we create instances of Rect and Circle and pass them to the measure function. This shows how different classes that implement the same interface can be used interchangeably.
To run this TypeScript code, you would typically compile it to JavaScript and then run it with Node.js:
This example demonstrates how TypeScript’s interfaces can be used to define shared behavior across different classes, enabling polymorphism and more flexible code design.