27

React Typescript allow to add custom data-* attributes. But is it possible to add custom attributes like 'name' || 'test' act. ?

<span name="I'm causing a type error" data-test="I'm Working"/>

Bold added by me.

type error: Type '{ children: Element; name: string; data-test: string; }' is not assignable to type 'DetailedHTMLProps, HTMLSpanElement>'. Property 'name' does not exist on type 'DetailedHTMLProps, HTMLSpanElement>'. TS232

"react": "^16.7.0",
"typescript": "^3.2.4",
Yaniv Peretz
  • 1,118
  • 2
  • 13
  • 22

4 Answers4

36

there is another way... skipping the static check (typescript don't do dynamic)

{ 
  const allowedProps = {test: "not-data-attribute"}
  <span {...allowedProps}/>
}
Yaniv Peretz
  • 1,118
  • 2
  • 13
  • 22
23

in react 16+ it is possible, see

probem is that typescript didnt know about it(yet)

but you can still add @ts ignore for typechecking

{ //@ts-ignore
  <span name="I'm causing a type error" data-test="I'm Working"/>
}
Juraj Kocan
  • 2,648
  • 1
  • 15
  • 23
  • Yes, that what I thought. Thanks. – Yaniv Peretz Feb 27 '19 at 08:56
  • I'm using React 17 with TypeScript, but my project still fails to compile because the property doesn't exist on the element (e.g. anchor tag). That blog post makes it sound like it should just work, am I missing something? – Yoshi Askharoun Aug 02 '21 at 13:26
5

simple add custom attribute start with data-, in some case you may start with aria-

<div data-attr={3} data-nothing="super">hover</div>

it seems typescript knows custom attribute with those prefix, check this link

lastStranger
  • 185
  • 2
  • 9
2

Create any file with extension .d.ts in your project and just extend the button interface in the JSX namespace. I'm using this for creating amp pages with React.

declare namespace JSX {
    interface ExtendedButton
        extends React.DetailedHTMLProps<
            React.ButtonHTMLAttributes<HTMLButtonElement>,
            HTMLButtonElement
        > {
        customAttribute?: string;
    }

    interface IntrinsicElements {
        button: ExtendedButton;
    }
}
svrakata
  • 21
  • 5