How to add attributes to HTML element in TypeScript

Are you using TypeScript, and trying to add an attribute or prop that doesn’t exist in the HTML element?

If so, you’ve come to right place to figure out how to get this working!

Here’s a little background on why this article is coming to be.

In this blog, I’m creating a beginners JavaScript course, and I’m using the <code> block, and it’s being written in React and TypeScript.

I wanted to add a rel attribute but the console yelled at me.


Type '{ children: string; rel: string; className: string; }' is not assignable to type 'DetailedHTMLProps, HTMLElement>'.
  Property 'rel' does not exist on type 'DetailedHTMLProps, HTMLElement>'.

The rel attribute is important to me because it’s what I use to add custom messages on top of every code block.

So here’s the solution I used.

Solution: Extend the HTMLAttributes interface

In the root of my project, I have a declartion.d.ts file, and wrote the following declaration:


import { AriaAttributes, DOMAttributes } from "react";

declare module 'react' {
  interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {
    rel?: string;
  }
};

Happy coding!

I like to tweet about TypeScript and post helpful code snippets. Follow me there if you would like some too!