Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Typescript not recognizing intrinsic attributes when extending HTMLAnchorElement

I have a simple anchor tag component that extends the native <a> tag.

I've defined my typescript interface to extend React.HTMLAttributes<HTMLAnchorElement>, but when I attempt to use component A and pass props like rel and target I get IntrinsicAttributes errors.

How can I extend the anchor tag properly?

Component definition:

interface Props extends React.HTMLAttributes<HTMLAnchorElement> {
  href: string;
  className?: string;
}

export const A: FC<Props> = ({ href, className, children, ...rest }) => {
  const baseClasses = "text-mb-green-200";
  const classes = `${baseClasses} ${className ? className : ""}`;

  return (
    <a {...rest} href={href} className={classes}>
      {children}
    </a>
  );
};

Attempted use:

<A {...rest} href={href} className={classes} rel={rel} target={target}>
   {children}
</A>

TS Error:

Type '{ children: ReactNode; href: string; className: string; target: string; }' is not assignable to type 'IntrinsicAttributes & Props & { children?: ReactNode; }'.
  Property 'rel' does not exist on type 'IntrinsicAttributes & Props & { children?: ReactNode; }'.ts(2322)
like image 216
marzipan Avatar asked Apr 08 '26 04:04

marzipan


1 Answers

Use React.AnchorHTMLAttributes instead of React.HTMLAttributes.

I found this out by looking in the node_modules/@types/react/index.d.ts file and doing a file-search for rel?:

interface Props extends React.AnchorHTMLAttributes<HTMLAnchorElement> {

}

enter image description here

like image 150
Monarch Wadia Avatar answered Apr 10 '26 17:04

Monarch Wadia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!