What Is an Interface in TypeScript?

By Hemanta Sundaray on 2023-04-08

In TypeScript, you can use the interface keyword to declare a custom type that describes the shape of an object. Essentially, a custom type is a type that is created by the programmer to fit the specific needs of their program or application.

An interface defines a set of properties and methods that an object must have in order to be considered compatible with that interface.

For example, let's say you have a function called addBookToLibrary that takes a book object as a parameter. The book object needs to have certain properties, like a name and author, in order for the function to work properly. But, there might be other properties that are optional, like the number of pages.

To ensure that the book object passed to addBookToLibrary meets these requirements, you can create an interface that specifies the expected properties and their types. This interface can then be used as a type annotation to check that the book object satisfies the requirements of the interface.

Now, let's take a look at an example of what this might look like in code.

How to Define an Interface?

interface Book {
  name: string
  author: string
  numPages?: number
}

When defining an interface, we start with the interface keyword followed by the name of the interface. In the example above, we have named the interface as Book. This interface defines the structure of a book object and specifies that a book object should have three properties: a name property of type string, an author property of type string, and an optional numPages property of type number.

Note: You can indicate an interface’s property is optional by including a ? before the : in its type annotation.

Now that we have defined the Book interface, we can use it to type annotate any object passed to the addToLibrary function, as shown below:

function addBookToLibrary(book: Book) {
  // Add book to library logic goes here
}

Now, if we try to pass an object that doesn't have the required properties or has properties of the wrong type to the addBookToLibrary function, TypeScript will throw an error.

Join the Newsletter