Gabrelsoft
3 min readSep 16, 2022

--

Difference between Type and Interface

In this article we would be looking at the difference between types and Interface in the Typescript programming language. Once we start exploring TypeScript, we start using interfaces and types without really understanding the differences between them. But, at some point, it becomes important to know the difference between the two.

Type and type aliases
TypeScript has primitive types such as boolean, number, string, etc. And if we want to declare advanced types, we use what are called type aliases. Type aliases refer to the process of creating a new name for a type. It is important to note that we are not defining a new type. The “type” keyword we use to do so might lead us to believe that we are creating a new type, but we are only giving a type a new name.

So whenever someone refers to types, the reference is aimed at type aliases.

Interfaces
Interfaces, on the contrary to types, are restricted to object types. They are a way to describe an object and its properties. Type alias declarations can be used for any primitive type, unions, or intersections. In that regard, interfaces are restricted to object types.

Let’s define compile time types for Point via interface and type alias and 2 implementation of getRectangleSquare function which will use both interface and type alias for parameter type annotation.

  1. One difference is, that interfaces create a new name that is used everywhere. Type aliases don’t create a new name — for instance, error messages won’t use the alias name.”

That not correct!

Let’s define compile time types for Point via interface and type alias and 2 implementation of getRectangleSquare function which will use both interface and type alias for parameter type annotation.

2. “A second difference is that type aliases cannot be extended or implemented from”

That not correct!

We can extend an interface with type alias:

We can extend an interface with type alias:

3. “type aliases cannot extend implement other types”

Again, that’s incorrect!

You can use interface or any other TypeScript valid type(which has shape of an Dictionary/JS Object, so non primitive types etc…) for type alias extension via intersection operator

The Difference?

  1. you cannot use extends on an interface with type alias if you use union operator within your type definition

2. Don’t use implements on a class with type alias if you use union operator within your type definition

3. Declaration merging doesn’t work with type alias
While declaration merging works with interfaces, it fails short with type aliases.

What I mean by declaration mergin?:

You can define same interface multiple times, and its definitions will merge into one:

Conclusion:

We’ve covered the difference between Typescript types and Interface and also talk about each of them.

If you like this article give it a thumbs up👍

--

--