TypeScript / Type Intersection
Posted On 01.02.2022
Let’s say, we are building a component to display some images (with lazy loading):
const LazyImage = (props: ImageProps) => {
...
}
And this component takes some properties (ImageProps
) that came from the two imaginary types:
type ImageSource {
imageUrl: string;
preloadUrl?: string;
}
type ImageMetadata {
fileSize: number;
width?: number;
height?: number;
}
The most inefficient way is to redefine everything from ImageSource
and ImageMetadata
into a new type ImageProps
:
type ImageProps {
imageUrl: string;
preloadUrl?: string;
fileSize: number;
width?: number;
height?: number;
}
The better way to do it, is to define a new ImageProps
that is an intersection between ImageSource
and ImageMetadata
with the &
operator:
type ImageProps = ImageSource & ImageMetadata
The order of the types when declaring an intersection doesn’t matter, so this will also work:
type ImageProps = ImageMetadata & ImageSource