5

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?

7
  • does that helps? stackoverflow.com/questions/27285856/… Commented May 11, 2023 at 13:58
  • 2
    @TheTisiboth - How do the answers to that question answer this question? Commented May 11, 2023 at 14:01
  • 2
    Apparently is part of Typescript specification for JSX, as per this answer stackoverflow.com/a/50961972/3797799 (referring to the doc). From my test, any prop with a - is considered valid by Typescript, ie. <div what-is-this="hello" >asd</div>. Commented May 11, 2023 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." Commented May 11, 2023 at 17:50
  • 1
    @T.J.Crowder, yes, I was thinking it was a duplicate but the question is not the same. Thanks for the heads up! Commented May 11, 2023 at 19:10

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.