reactjstypescriptjsxcustom-data-attribute

How TypeScript handles `data-*` attributes in JSX?


Consider this:

import type { JSX } from 'react';

const MyComponent = (): JSX.Element => (
  <div data-attr="bar">Foo</div>
);

This does not give any TypeScript error which is expected, however, I cannot find types for data-* custom attributes, something like

interface *** {
  // other attributes...
  `data-${string}`: string
}

Can anyone please tell me where in d.ts files are defining this?


Solution

  • It is part of Typescript specification for JSX, as per the documentation:

    Note: If an attribute name is not a valid JS identifier (like a data-* attribute), it is not considered to be an error if it is not found in the element attributes type.

    It also extends to any property with a dash - inside, for example this is valid JSX for Typescript:

    <div a-custom-attribute="hello"></div>