Middle
What is the difference between type and interface in TypeScript?
sobes.tech AI
Answer from AI
In TypeScript, type and interface are often used to describe object types, but there are differences:
-
Extensibility:
interfacecan be extended (extends) and merged (declaration merging), meaning multiple declarations with the same interface name are combined.typedoes not support declaration merging, but you can create unions and intersections of types.
-
Capabilities:
typeis more versatile — it allows describing not only objects but also unions, intersections, primitives, tuples, etc.interfaceis intended only for describing object structures and classes.
-
Syntax and preferences:
interfaceis often preferred for describing public APIs and classes because it supports declarative extension.typeis convenient for complex types, such as unions or mapped types.
Example:
interface IUser {
name: string;
}
interface IUser {
age: number; // interfaces will merge
}
const user: IUser = { name: 'Alice', age: 30 };
// type won't work this way:
// type User = { name: string };
// type User = { age: number }; // error: Duplicate identifier 'User'
// type allows unions:
type ID = string | number;