Intersection Types combine multiple types into one. This is useful when you want a type that has the properties of more than one type.
Example:
In the ArtworksResponse and ArtistsResponse, the types ArtworksData and ErrorHandling are combined to form a new type using the intersection operator &.
interface ErrorHandling {
success: boolean;
error?: { message: string };
}
interface ArtworksData {
artworks: { title: string }[];
}
interface ArtistsData {
artists: { name: string }[];
}
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);
};ArtworksResponseandArtistsResponseare created by intersectingArtworksDataorArtistsDatawithErrorHandling, meaning they will have the properties of both types.