TypeScript: Type vs Interface

Which are the differences between types and interfaces? A lot of people don’t know the differences since they are quite specific taking into account the potential behind them. In some cases, it doesn’t make sense to care a lot about them.

Before we continue you have to know what is TypeScript and what is involved in using it. You can find more information in this blog post.

Let’s get down, let’s get down to business 🎶

One of the main additional features that TypeScript provides is the definition of custom types. In TypeScript we can define shapes using the keyword type or interface.

Why interface is an option?

Since the ECMAScript 2015 standard, JavaScript allows us to use and define classes.

Historically, classes and interfaces form a strong relationship, with interfaces describing the blueprint of a class. Probably, you have read something like this multiple times: “a class implements an interface”. Basically for this reason interfaces exist in TypeScript.

So, in a nutshell, an interface is used to describe a piece of structural information in the same way that type does, but with a few subtle differences.

Working with the example

Imagine that we have these two shape definitions:

type Person = {
    name: string,
    id: string,
    age: number,
}

interface Student {
    name: string;
    id: string;
    age: number;
}

Interfaces and types seem to be entirely the same. Where are the differences? The biggest difference is the declaration merging.

Declaration merging for interfaces allows declaring an interface multiple times within the same file. TypeScript will combine and merge them internally into one interface.

As you can see in the example above, we can merge declarations and combine the properties and TypeScript will prompt an error whenever the type safety is not satisfied. The declaration merging cannot be used with types:

Why would someone declare the same interfaces multiple times in the same file? No one in their right mind would do something like this, wouldn’t they?

There is a special use case where declaration merging makes a lot of sense. In this blog post we will delve deeper into detail into this topic.

But, even so, at the end of the day, which option is the best one?

Some argue that the use of interfaces is preferable. If you prefer to delve deeper into the subject, you can find more information in this blog post by Nicholas Jamieson.

Others argue that the use of types is preferable for simplicity because there are few situations in which we need declaration merging.

My opinion is that we should use what makes us feel most comfortable, as long as we use it correctly. The differences are minimal, so the use of one or the other will be strictly limited by the limitations described in this post.

If you find any kind of error, something that it's not clear enough or you want me to drill down in more detail, don't hesitate to contact me.