Member-only story
What is the difference between Type and Interface in TypeScript?
TLDR; interface
is a way to describe data shapes, such as an object. Unlike an interface, type
can introduce a name for any kind of type, including primitive, union, and intersection types.
What is an Interface?
An interface looks like this:
Above we have defined an interface called Human
, and then used it to create a variable james
. Interfaces are useful in a way that we can always be sure that the objects that we create have the same shape (properties). And if we happen to create a variable with the interface Human
, with a different shape, TypeScript will show an error.
Simple enough? Good, let’s move on.
What is a Type?
When creating a type
, you’re not actually creating a new type, you’re creating a new name for a type, which is why it’s called a type alias.
Before you get too confused, here’s an analogy for you:
Ben have a laptop, but instead of calling it a laptop, he calls it his Code Maker, because Ben is edgy like that.
As we can see from above, the properties of type Laptop
and CodeMaker
are exactly the same. Why do we need to create another type with the exact same properties, just because Ben wants to call it a “Code Maker” instead of a laptop, like everybody else? That’s not very fair.
“If Ben gets to call his laptop a Code Maker, then I want to call mine The Machine”…