During my TypeScript journey, I kept getting confused by whether to use a type or an interface for type safety. I did some research on their differences and similarities, here’s what I learned!

🧵
Let’s start with the similarities. When it comes to describing the shape of your objects, it turns out both work pretty much the same. I do prefer using interfaces in this case, since describing an object’s shape is what interfaces were specifically designed to do.
What if you wanted to combine properties from one type or interface into another? This is also possible for both! It is known as “type intersection” for types and the “extends” keyword for interfaces. I like using interfaces in this case as I feel it reads a bit cleaner.
Need to provide some type safety to your functions? Also possible with both! I prefer using types in this case again for readability reasons.
Now let’s talk about the differences. With types, you are able to assign a type alias to a simple primitive type (string, number, boolean) if you’d like. This is not possible with interfaces. In addition, you are able to create union types (also not possible with interfaces).
With interfaces, you are able to do something called “declaration merging”. This allows you to declare multiple interfaces with the same name and TypeScript will merge all of declared interfaces together into one. This is not possible with types.
To summarize:

Use types for functions, assigning simple primitive types, and anytime you need more custom types with unions.

Use interfaces to describe your objects and for declaration merging.

In the end both are great options for providing type safety to your code!
You can follow @haagendaas.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled:

By continuing to use the site, you are consenting to the use of cookies as explained in our Cookie Policy to improve your experience.