Junior — Middle
What is the difference between types and interfaces in TypeScript, and what are their main functions?
sobes.tech AI
Answer from AI
In TypeScript, both types (type) and interfaces (interface) are used to describe data formats, but they have some differences and features.
-
Interfaces (interface):
- Used to describe the structure of objects.
- Support declarative extension (extends), allowing interfaces to be combined.
- Can be implemented by classes (implements).
- Allow declaration merging, meaning you can declare an interface with the same name multiple times, and they will merge.
-
Types (type):
- More versatile, can describe not only objects but also unions, intersections, primitives, tuples, etc.
- Do not support declarative extension, but new types can be created through unions (|) and intersections (&).
- Do not support declaration merging.
Main functions:
- Interfaces are well-suited for describing object and class contracts.
- Types are convenient for more complex and flexible descriptions, including unions and intersections.
Example:
interface IUser {
name: string;
age: number;
}
type ID = string | number;
type UserWithID = IUser & { id: ID };
Ultimately, the choice depends on the task: if you need flexibility and complex types — use type; if you need a contract for objects and classes — use interface.