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

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

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

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.

This post is also available on DEV.