antvaset.com
/
My blog
Declaring custom JSX/HTML attributes in TypeScript

Declaring custom JSX/HTML attributes in TypeScript

How to specify non-standard JSX/HTML attributes in TypeScript?

Published on by Anton Vasetenkov
Topics: TypeScript

Those who switched to TypeScript may experience problems with non-standard JSX/HTML props/attributes. React's type definition file (@types/react/index.d.ts) only includes standard HTML and React elements and props/attributes.

Consider, for example, that you need to allow the banana prop of type string on the <img> element. In TypeScript+JSX, the <img> element uses the React.ImgHTMLAttributes<T> interface declared in @types/react/index.d.ts as follows:

declare namespace React {
    //...
    interface ImgHTMLAttributes<T> extends HTMLAttributes<T> {
        alt?: string;
        crossOrigin?: "anonymous" | "use-credentials" | "";
        decoding?: "async" | "auto" | "sync";
        height?: number | string;
        // ...
    }
    //...
}

To allow the custom HTML attribute, add the banana?: string; member to the React.ImgHTMLAttributes<T> interface:

// Inside your types.d.ts
namespace React {
    interface ImgHTMLAttributes<T> {
        banana?: string;
    }
}

This approach makes use of interface merging, a form of TypeScript's declaration merging.

Thanks for stopping by my digital playground! If you want to say hi, you can reach out to me on LinkedIn or via email. I'm always keen to chat and connect.

If you really-really like my work, you can support me by buying me a coffee.