DEV Community

Cover image for What is a TypeScript Interface?
Aweys Ahmed
Aweys Ahmed

Posted on

1 1

What is a TypeScript Interface?

TypeScript Interface

Interfaces in TypeScript create a structure of what the object should contain. Think of how we created variables in the previous post and then stated what type the variable would accept. Interfaces allow us to do this with an object.

Let us imagine that we have a recreational basketball league and we want teams to register their players. However, we want to ensure that teams register their players with specific information. What we can do is create a basketball player interface and define its structure.


interface BasketballPlayer {
  firstName: string;
  lastName: string;
  jerseyNumber: number;
  position: string;
  currentTeam: string;
}
Enter fullscreen mode Exit fullscreen mode

Now that we have created a Basketball player interface, let's see how we can use this.

const registerPlayer = (registerPlayer: BasketballPlayer) => {
  console.log(registerPlayer);
}

let kingJames = {
  firstName: "Lebron",
  lastName: "James",
  jerseyNumber: 23,
  position: "All",
  currentTeam: "Lakers"
}

registerPlayer(kingJames);




# console.log output  { 
    firstName: "Lebron",
    lastName: "James",
    jerseyNumber: 23,
    position: "All",
  }

Enter fullscreen mode Exit fullscreen mode

Using the type of BasketballPlayer ensures that the correct information is submitted by all the teams and adds consistency to the application.

Any attempt to add other properties or omitting them will result in an error when being compiled.

We can also included properties that are optional. Let's assume that in our recreational league adding a nickname is optional. We could add that by adding ? after the property.

Here is what our BasketballPlayer type would like like with an optional nickname.

interface BasketballPlayer {
  firstName: string;
  lastName: string;
  jerseyNumber: number;
  position: string;
  currentTeam: string;
  nickName?: string;
}
Enter fullscreen mode Exit fullscreen mode

Nickname is now optional and allows some flexibility on adding properties that are not imperative.

In our next blog post, I'll review how we can use Interfaces with Classes.

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay