2 min read

TypeScript: Interfaces vs Types

In TypeScript, both Interfaces and Type Aliases can be used to describe the shape of an object or a function signature. While they are very similar and often interchangeable in modern TypeScript, there are distinct differences that determine when to use one over the other.

1. Syntax Comparison

Interface

Interfaces are primarily used to define the structure of objects (classes or object literals).

interface User {
  name: string;
  age: number;
}

Type Alias

Types can define objects, but they are also used for primitives, unions, and tuples.

type User = {
  name: string;
  age: number;
};

2. Key Differences

A. Declaration Merging (Interfaces Only)

Interfaces are "open" and can be merged. If you define an interface with the same name multiple times, TypeScript will automatically merge them into a single interface. This is a critical feature for extending third-party libraries.

interface Window {
  title: string;
}

interface Window {
  ts: any;
}

// Result: The Window interface now has both 'title' and 'ts' properties.

Types cannot do this. A type alias is closed once created; trying to redeclare it will throw an error.

B. Primitives, Unions, and Tuples (Types Only)

Interfaces can only describe object shapes. Types are more flexible.

// Union Type (One OR the other)
type Status = "pending" | "approved" | "rejected";

// Primitive
type Name = string;

// Tuple
type Point = [number, number];

C. Extensibility

Interface extends Interface:

interface Animal {
  name: string;
}

interface Bear extends Animal {
  honey: boolean;
}

Type Intersection:

type Animal = {
  name: string;
}

type Bear = Animal & {
  honey: boolean;
}

Note: Interfaces can extend Types, and Types can intersect with Interfaces.

3. Summary: When to use which?

  1. Use interface for defining object shapes, especially if you are writing a library or API that others might need to extend (via declaration merging).
  2. Use type when you need features interfaces don't support, specifically Unions (Type A | Type B) or Tuples.
  3. Consistency: Many teams prefer using interface by default for objects due to better error messages in some IDEs, switching to type only when necessary.

programming/javascript/typescript/typescript