In TypeScript, both interface
and type
can be used to define object types, but there are some differences. Here are the key distinctions:
- Extending types:
interface
allows extending other interfaces using theextends
keyword. On the other hand,type
allows extending using the&
(intersection) operation.
interface Person { name: string; } interface Employee extends Person { salary: number; }
type Person = { name: string }; type Employee = Person & { salary: number };
-
Multiple declarations:
interface
allows for declaring the same interface multiple times, merging definitions.type
does not support this feature. Therefore, theinterface
definition can be extended across multiple declarations. -
Complexity:
type
is more flexible thaninterface
, as it can represent not only objects but also other types such as unions, tuples, or aliases for primitive types. -
Compatibility:
type
can be more complex when combining different types, butinterface
offers better readability and structure.
In conclusion, both interface
and type
have their uses, and the choice between them depends on the context.