← Back to libraryQuestion 212 of 468
🔷TypeScriptIntermediate

Interfaces vs Type Aliases

📌 Definition:

Both interface and type describe object shapes. Interfaces are extendable and mergeable and are conventional for object/class contracts; type aliases are more flexible (unions, primitives, tuples, mapped types).

📖 Detailed Explanation:

interface User { id: number; name: string } and type User = { id: number; name: string } are largely interchangeable for object shapes. Differences: interfaces support declaration MERGING (declaring the same interface twice combines them) and are idiomatic for public object/class contracts and 'implements'. type can express things interfaces cannot: unions (type Status = 'pass' | 'fail'), primitives, tuples, and complex mapped/conditional types. Common guidance: use interface for object shapes and public APIs, type for unions and anything non-object. Both support extension (extends / &).

🔑 Key Points:
  • Both describe object shapes; often interchangeable
  • interface: declaration merging, idiomatic for classes/public APIs
  • type: unions, primitives, tuples, mapped/conditional types
  • Rule of thumb: interface for objects, type for unions/complex
🌍 Real-World Example:

Modeling an API payload: interface ApiUser { id: number; email: string; roles: string[] } gives every test that consumes response.json() as ApiUser autocomplete and error-checking on field names.

🎯 Scenario-Based Interview Question:

You need a type that is either 'admin' or 'qa' (a fixed set of strings). Interface or type, and why?