Sobes.tech
Middle

In TypeScript, types can be declared using the interface keyword and the type keyword. Briefly, what is the difference?

sobes.tech AI

Answer from AI

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

  • interface is intended for describing the structure of objects and supports declaration merging. This means you can declare the same interface multiple times, and TypeScript will merge them.

  • type is a more general tool that allows creating aliases for any types: primitives, unions, intersections, tuples, etc. However, type does not support declaration merging.

Example:

interface User {
  name: string;
}

interface User {
  age: number;
}

// Now User has both properties: name and age

// With type, this is not possible:
type UserType = {
  name: string;
};

// type UserType = {
//   age: number;
// }; // Error: Duplicate identifier 'UserType'

Overall, if you need to describe the structure of an object and plan to extend it, it's better to use interface. If you need a more complex type (for example, union or tuple), or an alias, then type.

In TypeScript, types can be declared using the… - sobes.tech