I see both 'type' and 'interface' used interchangeably in many tutorials. Are there specific scenarios in modern TypeScript versions where one is strictly better than the other, especially regarding performance or features like declaration merging and unions?
3 answers
In modern TypeScript, the gap has narrowed, but 'interface' is still preferred for objects that might be extended, thanks to declaration merging. If you define an interface twice, TS merges them, which is great for library authors. However, 'type' aliases are mandatory if you need to define unions, intersections, or primitives. For general application code, many teams now prefer 'type' for its consistency, but 'interface' can offer slightly better compiler performance in very large-scale projects with complex hierarchies.
Are there any specific scenarios where declaration merging in interfaces actually causes bugs by accidentally extending a type you didn't mean to?
I use 'interface' for public APIs and 'type' for everything else. It’s a simple rule that keeps the codebase very organized and easy to navigate.
That’s a solid rule of thumb, Karen. It follows the principle of being open for extension on your boundaries but closed for modification in your logic.
Yes, Charles! In large global namespaces, you can accidentally "pollute" an interface. This is why many prefer 'type' for internal application logic—it’s "final" and cannot be changed elsewhere, which prevents those weird, hard-to-track side effects in your type definitions.