TypeScript Developer interview question · Most asked
What are the differences between `interface` and `type` aliases?
Summary
Both can describe object shapes and be extended. Interfaces support declaration merging and extends, which reads well for object/class contracts; type aliases can name any type, including unions, tuples, primitives, mapped and conditional types.
Longer Answer
Interfaces with the same name in the same scope merge, which is used to augment library types (e.g., adding fields to Window or Express's Request). Type aliases can't be reopened. For object shapes, either is fine; many teams use interface for public object contracts and type for unions and computed types. Interface extends errors on conflicting properties, while intersections (&) may silently produce never properties.
Code Example
interface User { id: string; name: string }
interface User { email: string } // merged: { id, name, email }
type Status = "active" | "banned"; // only possible with type alias
type WithTimestamps<T> = T & { createdAt: Date; updatedAt: Date };
Key Points
- Interfaces: declaration merging,
extends - Types: unions, tuples, mapped/conditional types
- Both work for object shapes
- Use merging to augment library types
More most-asked TypeScript Developer questions
- What is TypeScript and what problems does it solve?
- What is structural typing in TypeScript?
- Explain `any`, `unknown` and `never`.
- What are discriminated unions and why are they powerful?
- What are generics and how do constraints work?
- Which built-in utility types do you use most, and what do they do?
- What is type narrowing and what techniques does TypeScript support?
- What are mapped types? Show how `Partial` or `Readonly` could be implemented.