DEV Community

Cover image for Use Custom HTML Attribute's in TypeScript
Luke Secomb
Luke Secomb

Posted on

Use Custom HTML Attribute's in TypeScript

Photo by Ningyu He on Unsplash

Installing different packages and frameworks means you run into some interesting problems with TypeScript. One recently was using custom HTML Attributes on DOM elements.

declare module 'react' {
  interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {
    // extends React's HTMLAttributes
    custom?: string;
  }
}
Enter fullscreen mode Exit fullscreen mode

This piece of code solved my issue, and allows you to add any custom HTML attributes when using TypeScript.

<div custom="no_ts_errors">
  your content here
</div>
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
seanblonien profile image
Sean Blonien

Do you know if it's possible to limit this to specific DOM elements? This allows all DOM elements to take 'custom' as an attribute, but what if we just wanted to limit it to 1 specific DOM element?

Collapse
 
svrakata profile image
svrakata • Edited

create any file with extension .d.ts in your project
and just extend the button interface in the JSX namespace

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

    interface IntrinsicElements {
        button: ExtendedButton;
    }
}
Enter fullscreen mode Exit fullscreen mode