Interfaces are a feature of TypeScript that allows us to define the structure or shape of an object and specify the properties and methods that an object has or should have. Their primary function is type checking and aiding developers in catching type-related errors during development.

Here, you can see a small example of how we can define an interface and apply it to an object.

interface Menu {
  breakfast: string;
  lunch: string;
  time: number;
}

const order: Menu = {
  breakfast: "Kachori",
  lunch: "daal bati",
  time: 12,
};

image.png

Interface for Functions

In addition to defining the types of objects, we can also use interfaces to type functions, their return values, and their arguments.

For example, we can do something like this:

image.png

image.png

Interfaces with Methods

we can also specify a method in a interface we can just create a gamer interface

image.png

Interfaces with Classes in TypeScript

TypeScript introduced support for the class keyword through ES2015. You can define classes with properties and methods like this:

class Car {
  brand: string = '';
  speed: number = 0;
}

const myCar = new Car();

But what if you want to make sure a class strictly follows a certain structure? That’s where interfaces come in.

We can define an interface and then use the implements keyword in the class to ensure it adheres to that interface: