TypeScript
/Intermediate
Interface vs Type Alias
Definition
The two primary ways to name a type in TypeScript. For most use cases they are functionally identical, but they have subtle differences in syntax, merging, and extending.
Explain Like I'm New
They are like two different brands of wrenches. 95% of the time, it doesn't matter which one you use to turn the bolt. The main difference is: Interfaces are open (you can add more to them later), and Types are closed (once defined, they cannot be mutated).
Real World Example
In React, many teams prefer `type Props = {}` for component props because they don't need to be extended later, but prefer `interface User {}` for global data models that might be augmented by third-party libraries.
Common Use Cases
- •Team coding standards
- •Library authoring
Interactive Example
// 1. SYNTAX DIFFERENCE interface UserI { name: string; } type UserT = { name: string; }; // 2. EXTENDING DIFFERENCE interface AdminI extends UserI { role: string; } type AdminT = UserT & { role: string }; // Uses Intersection (&) // 3. CAPABILITY DIFFERENCE (Only Types can do Unions) type ID = string | number; // interface ID = string | number; // ERROR: Interfaces must be objects // 4. MERGING DIFFERENCE (Only Interfaces can merge) interface Car { wheels: number; } interface Car { doors: number; } // Car now requires both wheels and doors! // type Bike = { wheels: number }; // type Bike = { gears: number }; // ERROR: Duplicate identifier
Interview Questions
basic
- What is one thing a `type` can do that an `interface` cannot?
intermediate
- What is Declaration Merging and which one supports it?
advanced
- How do error messages differ when using complex Interfaces vs Types?