#How to use typescript type-checking with the image component

4 messages · Page 1 of 1 (latest)

shut sinew
#

Say I have a component that displays an image with a specific style, how would I define type-checking with typescript so that the image src property is valid

---
import { Image } from 'astro:assets'

interface Props = {
    src: any; // How would I use type-checking here
    alt: string;
}
---
<Image src={Astro.props.src} alt={Astro.props.alt} />
plain depotBOT
#

Hi @shut sinew. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

You can use TypeScript to define the types of the props in your Astro component. In your case, you want to ensure that the src prop is valid. You can do this by importing the ImageMetadata type from Astro and using it to type your src prop. Here's how you can do it:

---
import { Image } from 'astro:assets'
import type { ImageMetadata } from 'astro';

interface Props {
    src: ImageMetadata | string; // Use ImageMetadata type for src
    alt: string;
}

const { src, alt } = Astro.props;
---
<Image src={src} alt={alt} />

In the above code, src can be either a string or an ImageMetadata object. If you're using the @astrojs/image integration, the imported image will be an ImageMetadata object which contains properties like src, width, height, and format. If you're not using the integration, the imported image will be a string.

If you want to access the properties of the ImageMetadata object, you can use a helper function to handle both cases:

function fixImgSrc(src: ImageMetadata | string) {
  return typeof src === "string" ? src : src.src;
}

Then you can use this function in your Astro component:

---
import { Image } from 'astro:assets'
import type { ImageMetadata } from 'astro';

interface Props {
    src: ImageMetadata | string;
    alt: string;
}

const { src, alt } = Astro.props;
---
<Image src={fixImgSrc(src)} alt={alt} />
#

Sources:


Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: