3

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?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Aelita
  • 87
  • 7
  • does that helps? https://stackoverflow.com/questions/27285856/how-do-i-dynamically-set-html5-data-attributes-using-react – TheTisiboth May 11 '23 at 13:58
  • 2
    @TheTisiboth - How do the answers to that question answer this question? – T.J. Crowder May 11 '23 at 14:01
  • 2
    Apparently is part of Typescript specification for JSX, as per this answer https://stackoverflow.com/a/50961972/3797799 (referring to the [doc](https://www.typescriptlang.org/docs/handbook/jsx.html#attribute-type-checking)). From my test, any prop with a `-` is considered valid by Typescript, ie. `
    asd
    `.
    – colinD May 11 '23 at 14:58
  • Relevant quote from those docs: *"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."* – T.J. Crowder May 11 '23 at 17:50
  • @colinD - I think that qualifies as an answer to this question, and the linked question's answers don't, quite. Good find! I suggest you post it. :-) – T.J. Crowder May 11 '23 at 17:51
  • 1
    @T.J.Crowder, yes, I was thinking it was a duplicate but the question is not the same. Thanks for the heads up! – colinD May 11 '23 at 19:10

1 Answers1

2

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>
colinD
  • 1,641
  • 1
  • 20
  • 22