Why does TypeScript programmers prefer interface over type

Viewed 662

I see a lot of TypeScript developers overuse interface. In fact they use it for almost everything even if their code is more functional than object oriented. Personally I prefer type which is more flexible and doesn't confuse if the interface is implemented by any class or it's used just to define object type. Are there any advantage to use interface over type or is it some kind of legacy thing that developers get used to do?

2 Answers

The intended use for type is for aliasing of types, especially intersection/union types.

They should not be used like an interface, as the documentation states:

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.

type Alias = { num: number }
interface Interface {
    num: number;
}
declare function aliased(arg: Alias): Alias;
declare function interfaced(arg: Interface): Interface;

An interface is a representation of what an entity should be ; specifically objects.

Interfaces are not only existing in Typescript, but in Java, C++ ... With different syntax but with the same meaning.

IMO :

interface is what you should use when describing what an object/class should be.

type in other hands should be considered as an alias maker.

Related