What is the difference between interface and type in TypeScript?
sobes.tech AI
Answer from AI
In TypeScript, interface and type are often used to describe types, but there are differences:
-
Extensibility:
interfacecan be extended (extends) and declarations with the same name can be merged, which is convenient for extending types in different parts of the code.typedoes not support declarative merging, but new types can be created through union (&) and intersection (|). -
Capabilities:
typeis more versatile — it can describe not only objects but also unions, intersections, primitives, tuples, etc.interfaceis only for describing objects and classes. -
Syntax:
interfaceis more declarative and readable, especially for describing data structures.
Example:
interface User {
name: string;
age: number;
}
type UserType = {
name: string;
age: number;
} | null;
Overall, if you need extensibility and declarativity — prefer interface. If you need flexibility and complex types — type.