Sobes.tech
Middle

What is the difference between interface and type in TypeScript? Why are interfaces needed if there are types and vice versa?

sobes.tech AI

Answer from AI

In TypeScript, both interface and type are used to describe data shapes, but there are important differences.

  • interface is intended for describing object structures and can be extended (extends) or implemented (implements) by classes. Interfaces support declaration merging, meaning you can declare an interface with the same name 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. Types cannot be extended or implemented, and they do not support declaration merging.

Why are both needed?

  • Interfaces are convenient for describing object and class contracts, especially when extensibility and declaration merging are important.
  • Types offer more flexibility for complex type expressions, such as unions or intersections.

Example:

interface IUser {
  name: string;
}

interface IUser {
  age: number; // interfaces 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;