In TypeScript, both ‘interface‘ and ‘type‘ are used to define custom types. Although they share some similarities, there are fundamental differences between them:
1. Declaration merging: Interfaces support declaration merging, while types do not. This means that you can define multiple interfaces with the same name, and TypeScript will merge them automatically. This can be useful when extending existing interfaces or providing multiple implementations.
Example:
interface User {
firstName: string;
}
interface User {
lastName: string;
}
// The resulting User interface will have both firstName and lastName
With types, if you declare two types with the same name, you'll get an error:
type User = {
firstName: string;
};
type User = {
lastName: string;
};
// Error: Duplicate identifier 'User'
2. Extending and implementing: Interfaces can extend other interfaces using the ‘extends‘ keyword, and classes can implement interfaces using the ‘implements‘ keyword. Types do not support these keywords, but you can achieve similar functionality using intersection types and mapped types.
Interface extending:
interface Person {
name: string;
}
interface Employee extends Person {
jobTitle: string;
}
Type intersection:
type Person = {
name: string;
};
type Employee = Person & {
jobTitle: string;
};
3. Syntax and instantiability: In general, interfaces offer a more flexible and idiomatic way to define structured types, while types are more suited for cases when you need to define union, intersection, or mapped types. However, some TypeScript constructs, like constructor types, can only be expressed as a ‘type‘, not an ‘interface‘.
Constructor type example:
type Constructable = {
new (...args: any[]): object;
};
4. Introspection and error messages: Types are more powerful in terms of introspection capabilities, like conditional types that can provide more fine-grained control over the resulting type. Additionally, error messages related to type aliases tend to be more informative.
Here’s a summary of the differences between ‘interface‘ and ‘type‘ in TypeScript:
[tab:my_label]
In conclusion, ‘interface‘ is recommended for defining structured object types and for type checking, while ‘type‘ should be used for more advanced use cases or when you need additional versatility like union and mapped types.