Sobes.tech
Middle

What is the difference between interface and type in TypeScript? Which do you prefer to use and in what situations?

sobes.tech AI

Answer from AI

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

  • interface is intended for describing object structures and supports declaration merging, which is convenient for extending types in different parts of the code.
  • type is more versatile: it can be used to describe not only objects but also unions, intersections, primitives, etc.

For example:

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

type ID = string | number;

type UserWithID = User & { id: ID };

I prefer to use interface for describing objects when extension and a clearer structure are needed, and type for complex unions or when describing not only objects. Overall, the choice depends on the task and the project style.

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