Middle
What is the difference between interface and type in TypeScript? What happens if you declare two interfaces with the same name?
sobes.tech AI
Answer from AI
In TypeScript, interface and type are often used to describe types, but there are differences:
-
interface is intended for describing the structure of objects and supports declaration merging. This means that if you declare two interfaces with the same name, they will automatically merge into one interface with combined properties.
-
type is an alias for a type that can describe not only objects but also unions, intersections, primitives, etc. Declaring two
types with the same name is not allowed — it will cause an error.
Example of interface merging:
interface User {
name: string;
}
interface User {
age: number;
}
const user: User = {
name: 'Alice',
age: 30
};
Here, two User interfaces merge into one with properties name and age. If these were types, the compiler would throw an error about re-declaration.