Sobes.tech
Middle

Is there a difference between type and interface in TypeScript?

sobes.tech AI

Answer from AI

In TypeScript, type and interface have similarities, but there are key differences:

  • Extensibility:

    • interface can be extended (extends) and augmented (declaration merging).
    • type cannot be augmented after declaration, but new types can be created based on existing ones through unions and intersections.
  • Capabilities:

    • type can describe not only objects but also primitives, unions, tuples, etc.
    • interface is only meant for describing object and class structures.
  • Usage:

    • interface is often preferred for describing public APIs and objects, as it supports declarative extension.
    • type is convenient for complex types, unions, and aliases.

Example:

interface User {
  name: string;
}

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

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

// type does not support merging

type ID = string | number;
Is there a difference between type and interface in… - sobes.tech