Typescriptintermediate7 min read
TypeScript Interfaces vs Types: When to Use Each
Understanding the differences between TypeScript interfaces and type aliases, and when to choose one over the other.
#typescript#interfaces#types#type-aliases
TypeScript provides two main ways to define custom types: interfaces and type aliases. While they often achieve similar results, they have distinct use cases and capabilities.
Key Differences
- Interfaces: Can be extended, can implement multiple interfaces, better for object shapes
- Types: Can create unions, intersections, primitives, more flexible for complex types
Code Example
typescript
// Interface - extensible
interface User {
name: string;
age: number;
}
interface AdminUser extends User {
permissions: string[];
}
// Type - flexible for unions
type ID = string | number;
type Status = "active" | "inactive" | "pending";
// Type - intersection
type Employee = User & {
employeeId: string;
};Output
// No output - type definitions only
💡
Remember This
- Use interfaces for object shapes that might be extended
- Use type aliases for unions, intersections, and primitive aliases
- Both can be used in most cases, but interfaces are preferred for public APIs
📌
Important Rules
- Prefer interfaces when defining object shapes that need extension
- Use types for unions, intersections, and complex type compositions
- Interfaces support declaration merging, types do not
⚠️
Common Mistakes
- Using types when interfaces would be more appropriate for object shapes
- Not leveraging declaration merging with interfaces
- Overcomplicating with type intersections when simple extension would work