Middle
When will you use interface yourself, and when type? Why do you prefer type?
sobes.tech AI
Answer from AI
In TypeScript, interface and type are often used to describe object types, but there are differences and preferences.
When to use interface:
- To describe the structure of objects and classes.
- When you need to extend types via
extendsor declarative interface merging. - If you plan to use declarative interface merging (e.g., to extend types from libraries).
When to use type:
- For union types, intersections, primitives, tuples, and other complex types.
- When you need greater flexibility in describing types.
- For aliases of primitives and complex type expressions.
Why I prefer type:
typeis more versatile and allows describing not only objects but also unions, intersections, primitives.- There are no restrictions on re-declaration, reducing the risk of unexpected merging.
- Often more convenient for complex types and composition.
Example of using type for union and object description:
type User = {
id: number;
name: string;
};
type Admin = User & {
role: 'admin';
};
type Guest = {
role: 'guest';
};
type Person = Admin | Guest;
While interface is more suitable for describing structure and extension:
interface User {
id: number;
name: string;
}
interface Admin extends User {
role: 'admin';
}