Typescript: Interface

Jatin Sharma - May 10 '23 - - Dev Community

In this article, you'll learn about what interface are and how to use them, along with the difference between type and interface. This article gives you a basic understanding of the interface.

This is going to be a full series of typescript where you will learn from basic topics like string, boolean to more complex like Type Aliases, enums, Interface, generics, and etc.

Table of Contents

Interface

An interface declaration is another way to name an object type. You can create it by using the interface keyword:

interface User {
    name: string,
    age: number,
}

// ✅ CORRECT
let newUser : User = {name: "John", age: 28};
// ❌ ERROR: property 'age' is missing
let newUser : User = {name: "John"};
// ❌ ERROR: missing the following properties from type 'User': name, age 
let newUser : User = {};
Enter fullscreen mode Exit fullscreen mode

You can also use readonly and optional approach in interface:

interface User {
    readonly id: number     // readonly variable
    name: string,
    age: number,
    specialKey? : string,   // optional 
}
Enter fullscreen mode Exit fullscreen mode

You can also pass functions to the interface, there are two ways to do that:

// Method-1
interface User {
    getDiscount(coupon: string): number     
}

// For Both you need to call this like this:
const newUser: User = {
    getDiscount: (coupon: "KIJ298DD9J") => {
        return 10;
    }
}

// Method-2
interface User {
    getDiscount: (coupon: string) => number
}

// 👉 You see I have changed the 'coupon' to 'couponName'
// You don't need to match the name of the parameter here
// It will take care of it
const newUser: User = {
    getDiscount: (couponName: "KIJ298DD9J") => {
        return 10;
    }
}
Enter fullscreen mode Exit fullscreen mode

In Method 1 you can simply use the () to say it functions like: getDiscount(): number and string are the return types, and it takes no arguments.

In Method 2 we use an arrow function like getDiscount: () => number.

Interface vs Type

Type aliases and interfaces are very similar, and in many cases, you can choose between them freely. Almost all features of an interface are available in type The key distinction is that a type cannot be reopened to add new properties vs. an interface that is always extendable.

Let’s Differentiate them with a few examples:

Adding new fields

In interface you can add new fields to the existing interface, but you cannot add new fields to an existing type. It will throw an error.

Interface

interface User {
    id: string;    
    email: string;
}

interface User {
    name: string;
}

// Now you can add all the three values to the User interface
const user: User = {
    id: "2323232",
    email: "foo@email.com",
    name: "Foo";
}
Enter fullscreen mode Exit fullscreen mode

Type

type User = {
    id: string;
}

type User = {
    email: string;
}

// ❌ ERROR: Duplicate identifier "User"
Enter fullscreen mode Exit fullscreen mode

In interface you can add new fields and change them however you want, but in type you can't do that. Once a type is created, it can't be changed.

Extends

To extend the already defined interface or type both have a different approach. interface uses extends keyword, while type uses intersection.

interface

interface Car {
    model: string;
    color: string;
}

// 👇 You can extend an interface using 'extends' keywords
interface Tesla extends Car {
  autoPilotModelName: string;
};

// ✅ Use Case
const newCar: Tesla = {
    model: "S",
    color: "red",
    autoPilotModelName: "xyz"
}
Enter fullscreen mode Exit fullscreen mode

type

type Car = {
    model: string;
    color: string;
}
// 👇 In type you need to use Intersection
type Tesla = Car & {
  autoPilotModelName: string;
};

const newCar: Tesla = {
    model: "S",
    color: "red",
    autoPilotModelName: "xyz"
}
Enter fullscreen mode Exit fullscreen mode

Union

In interface you cannot create a union type, but you can do that if you are using type. Let's take an example:

interface

interface User  {
    email: string;
}

interface Admin  {
    email: string;
    adminKey: string;
}

// ❌ ERROR: '{' expected.
interface Person = User | Admin;

// ✅ CORRECT: you can create union type like this
type Person = User | Admin;

// ✅ CORRECT: However you can use union type inside the interface
interface Person {
    person: User | Admin;
}
Enter fullscreen mode Exit fullscreen mode

type

type User = {
    email: string;
}

type Admin = {
    email: string;
    adminKey: string;
}

// ✅ You can do that.
type Person = User | Admin;
Enter fullscreen mode Exit fullscreen mode

In the above example, you might have noticed that when I tried to assign a union type to the interface (interface Person = User | Admin), it threw an error. It's because you cannot assign anything to interface. Its deceleration syntax is similar to class. But both have different working styles.

class MyClass {}

interface Hello {}
Enter fullscreen mode Exit fullscreen mode

Wrapping up

In this article, I have explained what interface is and how to use it, along with the difference between type and interface. This article gives you a basic understanding of the interface.

This is a series of Typescript lessons that will help you learn Typescript from scratch. If you enjoyed this article, then don't forget to give ❤️ and bookmark 🏷️for later use and if you have any questions or feedback then don't hesitate to drop them in the comments below. I'll see you in the next one.

Connect with me

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .