TypeScript ยท Chapter 17 of 44

Interfaces vs Type Aliases

Interfaces and type aliases both let you describe object shapes, and for many everyday cases they are interchangeable. However, there are a few differences worth knowing when choosing between them.

Interfaces support declaration merging, meaning you can define the same interface multiple times and TypeScript combines them. Type aliases cannot be redeclared, but they can represent things interfaces cannot, like unions and tuples directly.

Syntax
interface A { x: number }
type B = { x: number };

When to use interfaces

Prefer interfaces for defining object shapes, especially in public APIs, since they support extending with `extends` and declaration merging, which is useful for libraries.

When to use type aliases

Prefer type aliases when you need to describe unions, tuples, primitives, or more complex combined types that interfaces cannot express directly.

Example 1 (typescript)
interface Animal {
  name: string;
}
interface Animal {
  legs: number;
}

const dog: Animal = { name: "Rex", legs: 4 };
console.log(dog);
Output
{ name: 'Rex', legs: 4 }

Declaring Animal twice merges both declarations into a single interface, a feature type aliases lack.

Example 2 (typescript)
type Status = "success" | "error" | "loading";

function show(status: Status) {
  console.log(`Status: ${status}`);
}
show("loading");
Output
Status: loading

Type aliases can directly express a union of literal values, which interfaces cannot do.

Key points

  • Interfaces and type aliases are similar for describing object shapes.
  • Interfaces support declaration merging; type aliases do not.
  • Type aliases can describe unions and tuples directly; interfaces cannot.
  • Choose based on the feature you need, or team convention.
๐Ÿ’ก Note: Many style guides recommend interfaces for objects and type aliases for everything else, but both are valid choices.

๐Ÿ“ Quick Quiz

1. What feature do interfaces support that type aliases do not?

2. Which is better suited for describing a union of string literals?

3. Can two interfaces with the same name be merged?