Differences Between Type Aliases and Interfaces in TypeScript 4.6 | by Lee | Mar, 2022

Kind aliases and interfaces are very related, so which one ought to I exploit?

Photograph by Markus Winkler on Unsplash | Picture dimension altered

Kind aliases and interfaces are very related and can be utilized freely in lots of circumstances, however they nonetheless have sure variations and limitations. Subsequent, I’ll clarify them in numerous circumstances.

You possibly can see that sort aliases can outline primitive sorts (image, boolean, string, quantity, bigint, and so on.), whereas interfaces can’t.

Observe that it’s known as a kind alias as a result of it doesn’t create new sorts, however interfaces all the time create new sorts.

Union sorts may solely be outlined utilizing sort aliases.

Tuple sorts may solely be outlined utilizing sort aliases.

Each interface and sort can declare object sorts or operate sorts. However interface can declare the identical interface a number of instances, they are going to be merged routinely, whereas sort aliases is not going to merge and have to be distinctive.

One other key level is that sort aliases use intersection and interfaces use inheritance.

As proven within the error above, when interface inherits, the subtype can’t battle with the supertype, you may solely lengthen it, like this:

In order you may see, the interface makes use of extends to implement inheritance, and sort alias makes use of & to implement intersection.

In some circumstances, the automated merging and extensibility of interfaces may be helpful. Think about in case you made a third-party library and uncovered public APIs, customers may lengthen it via the interface mechanism, that’s nice!

So the suggestion right here is that if you wish to declare an object sort, please use interface first, and use sort aliases when wanted.

You possibly can see that mapped object sorts can solely be outlined utilizing sort aliases, together with the in key phrase and the keyof key phrase.

After we take care of unknown sorts, we are able to use typeof for sort seize, however then we are able to solely use sort aliases and never interfaces.

To sum up, sort aliases cowl virtually all of the options of interfaces, however interfaces are all the time extensible, whereas sort aliases aren’t. So you might want to decide on them based on particular circumstances.

Lastly, I’m Li. I'll proceed to output tales associated to frontend know-how. Should you like such tales and wish to assist me, please think about changing into a Medium member. It prices $5 monthly and offers you limitless entry to Medium content material. I’ll get somewhat fee in case you enroll through my link.That’s it — thanks.

More Posts