Joerg
Joerg

Reputation: 914

How to pass html attributes to child <img> element using React and Typescript without "IntrinsicAttributes & HTMLAttributes<HTMLImageElement> error"?

I have a functional React component that wraps an image element:

type BlobImageProps = HTMLAttributes<HTMLImageElement> & {
    blobId: string
}

function BlobImage(props: BlobImageProps){
    const {blobId, ...htmlAttributes} = props
    const [objectUrl, setObjectUrl] = useState<string>()
    // ...
    // ... load image blob using effect hook
    // ...
    return <img {...htmlAttributes} src={objectUrl}/>
}

And I use it like this:

function MyPage(){
    //...
    return (
        <BlobImage blobId="xyz1234" alt="Funny cats"/>
    )
}

However, I get a typeScript error saying

Type '{ blobId: string; alt: string; }' is not assignable to type 'IntrinsicAttributes & HTMLAttributes<HTMLImageElement> & { blobId: string; }'.
  Property 'alt' does not exist on type 'IntrinsicAttributes & HTMLAttributes<HTMLImageElement> & { blobId: string; }'.

What's wrong with my typing? What type should BlobImageProps have?

Upvotes: 3

Views: 5741

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074485

Looking through the React types definitions,¹ it looks like you're looking for ImgHTMLAttributes<HTMLImageElement> rather than HTMLAttributes<HTMLImageElement>.


¹ How I did that: I pasted your type definition into my editor, put my cursor on HTMLAttributes, and asked it to show me the definition (F12 in my case, VSCode). It took me to the index.d.ts for React (in @types/react in node_modules). I noted that that interface doesn't have alt (and doesn't use its type parameter for anything, which seems odd) so I searched for alt and found ImgHTMLAttributes.

Upvotes: 17

Related Questions