๐ŸŽ“ A1Learner
๐Ÿ”
0 of 42 lessons completed

TypeScript Interfaces vs Type Aliases

Interfaces and type aliases can both name an object shape. Each one also covers ground the other cannot write.

The same shape written both ways

One shape is written as an interface and again as an alias. Values of both types satisfy the same members.

interface UserShape {
  id: number;
  displayName: string;
}
type UserAlias = {
  id: number;
  displayName: string;
};
const first: UserShape = { id: 1, displayName: "Asha" };
const second: UserAlias = { id: 2, displayName: "Ravi" };
console.log(first.displayName);
console.log(second.displayName);

A union and a tuple need an alias

An interface cannot write a union or a tuple type. Both shapes below exist only because an alias names them.

type CartStatus = "open" | "closed";
type PointPair = [number, number];
const currentStatus: CartStatus = "open";
const pair: PointPair = [4, 9];
console.log(currentStatus);
console.log(pair[0]);
console.log(pair[1]);

Merging belongs to interfaces

Two blocks with one name merge into a single interface. An alias cannot be reopened in this way.

interface SettingsPanel {
  theme: string;
}
interface SettingsPanel {
  fontSize: number;
}
const panelSettings: SettingsPanel = { theme: "dark", fontSize: 14 };
console.log(panelSettings.theme);
console.log(panelSettings.fontSize);

Example

interface Invoice {
  id: number;
  total: number;
}
type InvoiceAlias = {
  id: number;
  total: number;
};
type PayMethod = "card" | "cash";
const firstInvoice: Invoice = { id: 10, total: 500 };
const secondInvoice: InvoiceAlias = { id: 11, total: 750 };
const method: PayMethod = "card";
console.log(firstInvoice.total);
console.log(secondInvoice.total);
console.log(method);

Key points

  • An interface names an object shape with declaration syntax.
  • A type alias can name unions, tuples and primitives as well as object shapes.
  • Declaration merging is available only to interfaces.
  • Interfaces extend with extends, and aliases combine shapes with intersections.
  • Use an interface for object shapes that may merge or be implemented, and an alias for unions, tuples and computed shapes.

In this example, the invoice shape works as both an interface and an alias, while the PayMethod union can only be written as an alias.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท TypeScript Playground

Exercise

Which type must be written with a type alias rather than an interface?