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 types, but there are differences:

  • Extensibility: interface can be extended (extends) and declarations with the same name can be merged, which is convenient for extending types in different parts of the code. type does not support declarative merging, but new types can be created through union (&) and intersection (|).

  • Capabilities: type is more versatile — it can describe not only objects but also unions, intersections, primitives, tuples, etc. interface is only for describing objects and classes.

  • Syntax: interface is more declarative and readable, especially for describing data structures.

Example:

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

type UserType = {
  name: string;
  age: number;
} | null;

Overall, if you need extensibility and declarativity — prefer interface. If you need flexibility and complex types — type.

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