Middle
What is the difference between interface and type in TypeScript? When should each be used?
sobes.tech AI
Answer from AI
In TypeScript, interface and type are often used to describe type shapes, but there are differences:
- interface is intended for describing object structures and can be extended (extends) or merged (declaration merging). This is convenient for defining contracts, especially in large codebases or when working with classes.
- type is more versatile: it allows creating aliases for primitives, unions, intersections, tuples, and other types. But
typedoes not support declaration merging.
When to use:
- Use
interfaceif you need to describe an object structure and plan to extend or merge interfaces. - Use
typeif you need to describe complex types, unions, intersections, or aliases for primitives.
Example:
interface User {
name: string;
age: number;
}
type ID = string | number;
type UserWithID = User & { id: ID };
Thus, interface is better suited for describing objects and extendable contracts, while type is for more complex or composite types.