foundation
type vs interface
Choose between aliases and interfaces for object shapes, unions, declaration merging, and public APIs.
Both `type` aliases and `interface` can describe object shapes. Interfaces are open to declaration merging and are common for public object contracts in libraries. Type aliases are more general: they can name unions, primitives, tuples, conditional results, and mapped type outputs.
type Result = { ok: true; data: string } | { ok: false; error: string };
interface User { id: string; name: string }
Pragmatic rule: use either consistently for object shapes in a codebase. Prefer `type` when you need unions or computed types. Know that `interface` merging can surprise teams when ambient declarations accumulate.
On interviews: avoid claiming one is always better. Explain extension differences and when declaration merging is intentional.
Common pitfalls: extending a union like an object shape; accidental global merging; style-only arguments without design impact.
The trade-off is often clarity versus safety or expressiveness versus maintainability. Checklist:
- Use `type` for unions and computed shapes.
- Know `interface` merging behavior.
- Keep public contracts consistent.