Declaring custom JSX/HTML attributes in TypeScript

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 like this:

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

See also

Leskoff Big Phonetic Transcriptions image
Big Phonetic Transcriptions
$29.99

A collection of phonetic transcriptions showcasing the beauty of phonetic notation.

Leskoff оптимизм IPA Transcription Poster image
оптимизм IPA Transcription Poster
$14.99

A poster featuring the phonetic transcription of "оптимизм" in the International Phonetic Alphabet (IPA).

Leskoff Cubane Molecule Poster image
Cubane Molecule Poster, Ball-and-Stick Model, English-Labeled
$19.99

A poster featuring the ball-and-stick model of the cubane molecule.

Leskoff Carian Alphabet Poster image
Carian Alphabet Poster, English-Labeled
$17.99

The Carian alphabet chart.

Leskoff сообщество Morphemic Analysis Poster image
сообщество Morphemic Analysis Poster
$14.99

A poster featuring the morphemic analysis of the Russian word сообщество.

TypeScript Validator

Validate JSON against TypeScript types and interfaces.

Walking a directory in Node.js

How to list all files recursively within a directory tree in Node.js?

Font Viewer

An online font viewer.

Egyptology Crossword

A daily crossword puzzle for Egyptological terms.

SoundFont Player

Preview and test SoundFonts online.

All prices listed are in United States Dollars (USD). Visual representations of products are intended for illustrative purposes. Actual products may exhibit variations in color, texture, or other characteristics inherent to the manufacturing process. The products' design and underlying technology are protected by applicable intellectual property laws. Unauthorized reproduction or distribution is prohibited.