I'm attempting to type an async arrow function that can take a single image object or an array of image objects.
TypeScript overloading is new to me and I may be doing everything completely wrong.
Here the attempt.
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 type
async (images)
?
If I useimages: ImageType | ImageType[]
the map complains.Property 'map' does not exist on type 'ImageType | ImageType[]'. Property 'map' does not exist on type 'ImageType'.ts(2339)
Once
images
is properly typed is there a better way to test forisImagesAnObject
? I thought something likeimages isinstanceof ImageType
but that was a fail.