DEV Community

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

Posted on

11

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

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️