Trying to create an async arrow function that can handle a single image object or an array of image objects.
I'm new to TypeScript overloading and may be approaching this the wrong way.
Here's what I've come up with:
type ImageType = {
uri: string;
type?: string;
height?: number;
width?: number;
};
type ConvertImagesToJpegParams = {
(param: ImageType): Promise<ImageType>;
(param: ImageType[]): Promise<ImageType[]>;
};
const convertImagesToJpegAsync: ConvertImagesToJpegParams = async (images) => {
const isImagesAnObject = typeof images === 'object';
const imagesToConvert = isImagesAnObject ? [images] : images;
let convertedImages = [];
const convertImageToJpegPromises = imagesToConvert.map(async (image) => {
// do stuff that converts the image.
});
await Promise.all(convertImageToJpegPromises);
return isImagesAnObject ? convertedImages[0] : convertedImages;
};
How should I define the types for
async (images)
?
If I specifyimages: ImageType | ImageType[]
, the map function gives an error.Property 'map' does not exist on type 'ImageType | ImageType[]'. Property 'map' does not exist on type 'ImageType'.ts(2339)
Once
images
is correctly typed, is there a more efficient way to check ifisImagesAnObject
? I tried something likeimages instanceof ImageType
but it didn't work.