[Typescript] Comparing Intersection and Interface Extends in TypeScript
One common question is whether to use type
or interface
in TypeScript.
To clarify the difference, type
can represent anything, including objects, whereas interface
primarily represents object types.
Given the significance of object types in TypeScript and the broader context of JavaScript, interfaces are particularly important.
However, unions, which can be handled by type, are also very significant.
Intersections versus Interface Extends
A more interesting comparison to make is intersections vs interface extends
.
The intersection and interface extend can both be used to combine types, but their functionality differs.
TypeScript prefers interface extends
for a simple reason: caching.
TypeScript can cache interfaces based on their names, effectively creating a reference for future use. On the other hand, intersections require the TypeScript to compute it almost anew each time it's used, largely due to their potentially complex nature. Therefore, TypeScript recommends the use of interface extends
over intersections wherever possible.
You can read more about the implications of preferring interfaces over intersections on TypeScript's performance here.