Sobes.tech
Middle

What is the difference between type and interface in TypeScript?

sobes.tech AI

Answer from AI

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

  • Extensibility:

    • interface can be extended (extends) and merged (declaration merging), meaning multiple declarations with the same interface name are combined.
    • type does not support declaration merging, but you can create unions and intersections of types.
  • Capabilities:

    • type is more versatile — it allows describing not only objects but also unions, intersections, primitives, tuples, etc.
    • interface is intended only for describing object structures and classes.
  • Syntax and preferences:

    • interface is often preferred for describing public APIs and classes because it supports declarative extension.
    • type is convenient for complex types, such as unions or mapped types.

Example:

interface IUser {
  name: string;
}

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

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

// type won't work this way:
// type User = { name: string };
// type User = { age: number }; // error: Duplicate identifier 'User'

// type allows unions:
type ID = string | number;
What is the difference between type and interface in… - sobes.tech