Type Aliases | Typescript
Interfaces vs. Type Aliases#
As we mentioned, type aliases can act sort of like interfaces; however, there are some subtle differences.
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.
In the code below, hovering over interfaced in an editor will show that it returns an Interface, but will show that aliased returns object literal type.
In older versions of TypeScript, type aliases couldn't be extended or implemented from (nor could they extend/implement other types). As of version 2.7, type aliases can be extended by creating a new intersection type e.g. type Cat = Animal & { purrs: true }.
Because an ideal property of software is being open to extension, you should always use an interface over a type alias if possible.
On the other hand, if you can't express some shape with an interface and you need to use a union or tuple type, type aliases are usually the way to go.
Interface vs Type aliases Summary:#
you cannot use
implementson anclasswith type alias if you use union operator within your type definition- Which makes complete sense! A class blueprint, cannot implement one or another shape structure, so nothing surprising on this front.
you cannot use
extendson aninterfacewith type alias if you use union operator within your type definition- similarly to class
implementsusage, interface is a "static" blueprint — it cannot exists in one or another shape
- similarly to class
declaration mergingdoesn’t work with type alias- always use interface for public API's definition when authoring a library or 3rd party ambient type definitions