Back to Typescript Topics
Typescriptintermediate Level 7 min read Afzaal Suleman

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 Study Chapter ยท Official Reference

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 Demonstration & Syntax

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
๐Ÿ“–

Chapter Rules & Key Notes

๐Ÿ’ก

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
โœฆโœฆโœฆ