Typescript: Interfaces vs Types

In this article we are discussing the differences between Interfaces and Types in TypeScript.

Type

Type or "type alias" allows the creation of a new name for a type. Aliasing doesn't actually create a new type - it creates a new name to refer to that type. One of the key differences is that a type can name primitives, unions, tuples and other types. And this is how it looks:

// creating a type
type User = {
  name: string;
  age: number;
}

// using a type

const myUser: User = {
  name: "John",
  age: 33
};

Interface

As discussed in this article interfaces provide a very powerful way of to define entities that most conform a definition and seemingly defining an interface looks the same as defining a type:

// creating an interface
interface User {
  name: string;
  age: number
}
// using an interface
const myUser: User = {
  name: "John",
  age: 33
};

Differences

Interfaces have many similarities to types however interfaces provide us with more capabilities and therefore they are preferred.

An interface, for example, can be used in conjunction with the extends and implements keywords, whereas a type alias for an object cannot. An interface can also have multiple merged declarations, and a type alias for an object type literal cannot.

The last sentence means that interface can be merged, which really means that if you have two interfaces with the same name, TypeScript merges them together:

// merged interfaces
interface User {
  name: string;
  age: number
}

interface User {
  email: string;
}
// using the merged interface
const myUser: User = {
  name: "John",
  age: 33,
  email: "me@test.com"
};

The same cannot be done with type aliases - when you attempt to do that, you'll be presented with a "Duplicate identifier 'User'" error.