Senior
What is the difference between types and interfaces in TypeScript?
sobes.tech AI
Answer from AI
In TypeScript, both type and interface are used to describe types, but there are differences:
- interface is intended for describing object structures and supports declaration merging. This is convenient for extending types across different parts of the code.
- type is more versatile: it allows creating aliases for primitives, unions, intersections, and other types, not just objects.
Example:
interface IUser {
name: string;
age: number;
}
type ID = string | number;
type UserWithID = IUser & { id: ID };
If you need to describe complex types with unions or intersections, it's better to use type. For describing objects and enabling extension — interface. In recent versions of TypeScript, the boundaries between them have become less strict, and the choice often depends on the style and requirements of the project.