How to create interfaces in TypeScript

Interfaces and Classes are used to create custom types in TypeScript. These are similar but also have significant differences which I want to mention below.

Aneeqa Khan
2 min readJan 2, 2023

Difference between Interfaces and Classes

Interfaces

  • Define a new type
  • Properties (signatures)
  • Methods (signatures)
  • Cannot be instantiated

Classes

  • Define a new type
  • Properties (with implementation)
  • Methods (with implementation)
  • Can be instantiated

Create an Interface

interface keyword is used to create an interface following the name of the interface.

interface Employee {
name: string;
title: string;
}

Here Employee represents the interface name with 2 string properties 'name' and 'title'.
Let's look into a complex example

interface Manager extends Employee {
department: string;
numOfEmployees: number;
scheduleMeeting: (topic: string) => void;
}

Now this Manager interface inherits all the properties of Employee interface. So in other words Manager interface has 4 properties i.e., name, title, department, and numOfEmployees.
As I mentioned above, interfaces don't have method implementations. So any object that inherits Manager interface will define the scheduleMeeting method according to it.

Implement an Interface

Any object that implements above mentioned Employee interface must have 2 properties with string types.

let newEmployee1: Employee = {
name: 'Sarah',
title: 'Software Engineer',
}

Let’s see another example

let newEmployee2: Employee = {
name: 'James',
title: 'Team Lead',
teamName: 'Alpha squad'
}

Now newEmployee2 have one additional property teamName but it still inherits the Employee interface because as long as an object has all the required properties of an interface can inherit/extends an interface.
This is also called a Structural Type System.

An optional member of the interface

We can also declare optional members of the interface just like we did in optional params in a function.

interface Person {
firstName: string;
lastName: string;
midName?: string;
}

While implementing an interface, we can skip optional members of an interface, and the compiler won’t give any error.

Thank you for reading!
Feel free to connect on Twitter

--

--

Aneeqa Khan
Aneeqa Khan

Written by Aneeqa Khan

I’m a frontend web and mobile developer specialized in web/mobile designs and frontend frameworks. I usually work with React, React Native, Next and TypeScript.

No responses yet