TypeScript by Example: Intersections
Merging multiple type definitions into unified contracts using intersection types. This sample code demonstrates combining interfaces with the ampersand operator, creating composite types for API responses, and building complex structures from reusable type components.
Code
interface ErrorHandling {
success: boolean;
error?: { message: string };
}
interface ArtworksData {
artworks: { title: string }[];
}
interface ArtistsData {
artists: { name: string }[];
}
// Intersection type
type ArtworksResponse = ArtworksData & ErrorHandling;
type ArtistsResponse = ArtistsData & ErrorHandling;
const handleArtistsResponse = (response: ArtistsResponse) => {
if (response.error) {
console.error(response.error.message);
return;
}
console.log(response.artists);
};Explanation
Intersection types combine multiple types into one. This allows you to add together existing types to get a single type that has all the features you need. We use the ampersand & to create an intersection.
For example, Person & Serializable & Loggable means an object of this type will have all members of Person, and all members of Serializable, and all members of Loggable.
This is commonly used for mixins or when handling API responses where you might have a standard error/status structure combined with specific data structures.
Code Breakdown
interface ErrorHandling defines common error structure.interface ArtworksData defines specific data structure.ArtworksData & ErrorHandling combines both interfaces into one type.response: ArtistsResponse requires all properties from both types.
