Skip to main content

Typescript: Interfaces vs Types

2 min read

Older Article

This article was published 8 years ago. Some information may be outdated or no longer applicable.

Let’s look at the differences between interfaces and types in TypeScript. They seem identical at first glance. They’re not.

Type

A type (or “type alias”) lets you create a new name for a type. It doesn’t actually mint a new type. It just gives you a different label to refer to an existing one. One key difference: a type can name primitives, unions, tuples, and other types. Here’s what it looks like:

// 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 give you a powerful way to define entities that must conform to a particular shape. Defining an interface looks almost identical to defining a type:

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

Differences

Interfaces share a lot of ground with types, but they hand you a few extra capabilities. That’s why they tend to be the preferred choice.

An interface works with the extends and implements keywords. A type alias for an object can’t do that. An interface also supports declaration merging. A type alias doesn’t.

Declaration merging means that if you define two interfaces with the same name, TypeScript squashes 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',
};

Try the same trick with type aliases and you’ll get a “Duplicate identifier ‘User’” error.