Correctly typing ImageFieldImage to pass as component prop

I have created a slice for a carousel. The slice contains a group with an image field. I am extracting the images from the slice like this:

const carouselImages: ImageFieldImage[] = slice.primary.slides.map((slide) => slide.slide_image)

And then passing the carouselImages array to the Carousel component:

<CarouselFC images={carouselImages}/>

The carousel component is defined as:

interface CarouselProps {
    images: ImageFieldImage[] | null | undefined;
}

const CarouselFC = ({images}: CarouselProps) => {
     if (images !== null && images !== undefined) {
          ...

However, in the carousel component I am getting a Typescript warning that the field param is not correctly typed for PrismicNextImage.

const currentImage = images[currentIndex] as ImageFieldImage;
{currentImage &&
                <PrismicNextImage field={currentImage} fallback={<p>Loading...</p>}/>
                }

The error is:

Type ImageFieldImage is not assignable to type ImageFieldImage | null | undefined
Type FilledImageFieldImage is not assignable to type ImageFieldImage | null | undefined
Type FilledImageFieldImage is missing the following properties from type FilledImageFieldImage: id, edit
PrismicNextImage.d.ts(9, 5): The expected type comes from property field which is declared here on type
IntrinsicAttributes & Omit<ImageProps, "src" | "alt"> & {     
  field: ImageFieldImage | null | undefined;     
  imgixParams?: { ...; } | undefined;     
  alt?: "" | undefined;     
  fallbackAlt?: "" | undefined;     
  fallback?: ReactNode; 
}

The image does display correctly, but the red squiggly in the IDE drives me crazy and I'd prefer not to suppress it. This seems like it should be simple, so I may be missing something. Any help is appreciated!

Hey @asummers, thanks for reaching out, and sorry for the delay getting back to you,

Can you share the output of the following command with us?

npm ls @prismicio/client

I'm thinking you might be using an outdated version of the client, causing this mismatch in your types. If the above logs multiple instance of @prismicio/client (not deduped), you could try updating your client to fix it: npm update @prismicio/client

If you're still using @prismicio/types to type Prismic fields, you can easily migrate to types that are now exported by @prismicio/client directly. See this part of the related migration guide to help you on that: @prismicio/client v7 Migration Guide - Documentation - Prismic

Let us know about it :slight_smile:

I was actually able to get this working and was overcomplicating things.

2 Likes