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.

Related projects

Visualizing the hierarchy of FHIR data types and resources.
FHIR, TypeScript
How to list all files recursively within a directory tree in Node.js?
Node.js, JavaScript, TypeScript
Explore the HL7 Reference Information Model.
HL7 RIM, TypeScript
Browse the PCORnet Common Data Model.
PCORnet, TypeScript
Browse the OMOP Common Data Model.
OMOP, TypeScript
Validate JSON against TypeScript types and interfaces.
TypeScript, JSON
Explore the content model behind SNOMED CT.
SNOMED CT, TypeScript
Browse the SDTM model.
SDTM, TypeScript

Made by Anton Vasetenkov.

If you want to say hi, you can reach me on LinkedIn or via email. If you like my work, you can support me by buying me a coffee.