Middle
How do type and interface differ in TypeScript? When do you use each?
sobes.tech AI
Answer from AI
In TypeScript, type and interface are often used to describe object types, but there are differences:
-
interface is intended for describing the structure of objects and can be extended (
extends) or implemented (implements) in classes. Interfaces support declaration merging, meaning you can declare an interface with the same name in multiple places, and they will merge. -
type is more versatile: it can describe not only objects but also unions, intersections, primitives, tuples, etc. However,
typedoes not support declaration merging.
When to use:
- If you need to describe an object structure, especially if you plan to extend or merge,
interfaceis better. - If you need a more complex type (union, intersection, primitives),
typeis suitable.
Example:
interface User {
name: string;
}
interface User {
age: number; // interfaces merge
}
const user: User = { name: "Alice", age: 30 };
// type does not support merging
// type User = { name: string };
// type User = { age: number }; // error
// type for union types
type ID = string | number;