Sobes.tech
Middle

What is the difference between type and interface in TypeScript? What are the pros and cons of each?

sobes.tech AI

Answer from AI

In TypeScript, type and interface are used to describe types, but they have differences and features.

interface:

  • Designed to describe the structure of objects and classes.
  • Supports declaration merging, meaning you can declare an interface with the same name in multiple places, and they will merge.
  • Can extend other interfaces using extends.
  • Used for describing contracts, especially in OOP.

type:

  • More versatile, allows describing not only objects but also unions, intersections, primitives, tuples, etc.
  • Does not support declaration merging (cannot be declared multiple times with merging).
  • Can create complex types using operators like |, &.

Pros and cons:

Feature interface type
Extension Yes, via extends and merging Yes, via intersections (&), but no merging
Versatility Only objects and classes Any types (primitives, unions, tuples)
Declaration merging Yes No

When to use what:

  • If you need to describe the structure of an object or class, it's better to use interface.
  • If you need a complex type (union, intersection, primitives), type is better.
  • For extendable APIs, interface is more convenient.

Example:

interface IUser {
  name: string;
}

interface IUser {
  age: number; // interfaces will merge
}

const user: IUser = { name: "Alice", age: 30 };

// type does not support merging
// type User = { name: string };
// type User = { age: number }; // error

// type for union types
type ID = string | number;