Middle
Is there a difference between type and interface in TypeScript?
sobes.tech AI
Answer from AI
In TypeScript, type and interface have similarities, but there are key differences:
-
Extensibility:
interfacecan be extended (extends) and augmented (declaration merging).typecannot be augmented after declaration, but new types can be created based on existing ones through unions and intersections.
-
Capabilities:
typecan describe not only objects but also primitives, unions, tuples, etc.interfaceis only meant for describing object and class structures.
-
Usage:
interfaceis often preferred for describing public APIs and objects, as it supports declarative extension.typeis convenient for complex types, unions, and aliases.
Example:
interface User {
name: string;
}
interface User {
age: number; // interfaces will merge
}
const user: User = { name: "Alice", age: 30 };
// type does not support merging
type ID = string | number;