Better Programming

Advice for programmers.

Follow publication

Differences Between Type Aliases and Interfaces in TypeScript 4.6

Zachary Lee
Better Programming
Published in
2 min readMar 14, 2022
Photo by Markus Winkler on Unsplash | Image size altered

Type aliases and interfaces are very similar and can be used freely in many cases, but they still have certain differences and limitations. Next, I will explain them in different cases.

Primitive Types

You can see that type aliases can define primitive types (symbol, boolean, string, number, bigint, etc.), whereas interfaces cannot.

Note that it’s called a type alias because it doesn’t create new types, but interfaces always create new types.

Union Types

Union types can also only be defined using type aliases.

Tuple Types

Tuple types can also only be defined using type aliases.

Objects / Functions Types

Both interface and type can declare object types or function types. But interface can declare the same interface multiple times, they will be merged automatically, while type aliases will not merge and must be unique.

Another key point is that type aliases use intersection and interfaces use inheritance.

As shown in the error above, when the interface inherits, the subtype cannot conflict with the supertype, you can only extend it, like this:

So as you can see, the interface uses extends to implement inheritance, and type alias uses & to implement intersection.

In some cases, the automatic merging and extensibility of interfaces can be useful. Imagine if you made a third-party library and exposed public APIs, users could extend it through the interface mechanism, that’s great!

So the suggestion here is that if you want to declare an object type, please use the interface first, and use type aliases when needed.

Mapped Object Types

You can see that mapped object types can only be defined using type aliases, including the in keyword and the keyof keyword.

Unknown Types

When we deal with unknown types, we can use typeof for type capture, but then we can only use type aliases and not interfaces.

To sum up, type aliases cover almost all the features of interfaces, but interfaces are always extensible, while type aliases are not. So you may need to choose them according to specific cases.

That’s all for today. Thanks for reading.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Write a response