Sobes.tech
Middle

What is the difference between interface and type in TypeScript?

sobes.tech AI

Answer from AI

In TypeScript, interface and type are often used to describe object shapes, but there are differences:

  • interface is designed for describing object structures and can be extended (extends) and merged (declaration merging). This is convenient for defining contracts and APIs.
  • type is more versatile: it allows creating aliases for primitives, unions, intersections, tuples, and other types, except objects.

Example:

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

type ID = string | number;

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

The main difference is — interface can be extended and declarations can be merged, whereas type cannot. In newer versions of TypeScript, the capabilities of type have expanded, but for describing objects with extendability, interfaces are often preferred.

What is the difference between interface and type in… - sobes.tech