HACKER Q&A
📣 KorematsuFredt

Does any one know why TypeScript has both Interfaces and Type aliases?


Of course I have read the docs and I know the subtle differences. But I also do not see how the design proposal to have two language features so identical both could have possibly passed a review of peers.

I am not familiar with how Typescript develops. Is there some RFP one can refer to ?

I suspect the reasons for these two features is historical, backward compatibility as such but I could not find any meaningful discussion on the topic.


  👤 frankacter Accepted Answer ✓
TypeScript has both interfaces and type aliases because they serve different purposes.

Interfaces are used to define the shape and behavior of an object. They are a way of enforcing contracts between different parts of your code. For example, you could define an interface for a Person object that specifies that it must have a name property and a age property. This would ensure that any code that uses the Person interface knows what properties to expect.

Type aliases are used to create new names for existing types. This can be useful for making your code more readable and maintainable. For example, you could create a type alias called MyDate that is equivalent to the Date type. This would allow you to use the MyDate type throughout your code, which would make it easier to understand what types of values are being used.

In my use I find interfaces are a good choice for defining the shape and behavior of objects, while type aliases are a good choice for creating new names for existing types.

Some other considerations in how they are differentiated are that:

* Interfaces are open and can be extended, Alias cannot.

* Interfaces can be interested with other types, Alias cannot.

* Interface supports declaration merging, Alias does not.

While not an RFP, this may be helpful:

https://github.com/microsoft/TypeScript/wiki/Performance#pre...