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} />