5 min read
•Question 3 of 48mediumWhat is the difference between type and interface?
Understanding when to use type vs interface.
What You'll Learn
- Differences between type and interface
- When to use each
- Best practices
Comparison
| Feature | Type | Interface |
|---|---|---|
| Extend | & (intersection) | extends |
| Declaration merging | No | Yes |
| Primitives/Unions | Yes | No |
| Computed properties | Yes | No |
Interface
code.tsTypeScript
interface User {
name: string;
age: number;
}
// Extending
interface Admin extends User {
role: string;
}
// Declaration merging
interface User {
email: string; // Merges with above
}Type
code.tsTypeScript
type User = {
name: string;
age: number;
};
// Extending with intersection
type Admin = User & {
role: string;
};
// Union types (interface can't do this)
type Status = "pending" | "approved" | "rejected";
// Primitive types
type ID = string | number;Best Practice
- Use interface for object shapes that might be extended
- Use type for unions, primitives, and complex types
- Be consistent within your codebase