Middle
What are the similarities and differences between types and interfaces in TypeScript? When to use each?
sobes.tech AI
Answer from AI
In TypeScript, both type and interface are used to describe object types, but there are differences:
- interface supports declaration merging, meaning you can declare an interface with the same name in different places, and they will merge.
- type is more versatile: it can describe not only objects but also unions, intersections, primitives, etc.
- Interfaces are better suited for describing public APIs and objects, especially if extension is expected.
- Types are convenient for complex type combinations and when greater flexibility is needed.
Example:
interface IUser {
name: string;
age: number;
}
type ID = string | number;
type UserWithID = IUser & { id: ID };
If you need extensibility and declarativity — choose interface. If you need complex type composition — type."}]}]}