Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to properly set prop type in React using Typescript

I have a react component called LinkButton, and it has the following props. I’ve been having issues with correctly setting the prop type of the link prop.

interface IProps {
  text?: string;
  onClick?: (e: React.SyntheticEvent<HTMLAnchorElement>) => void;
  type?: ButtonType;
  link: string | {
    pathname: string;
    state: { from: string};
    hash: string;
  };
  target?: React.HTMLAttributeAnchorTarget;
  useAnchorTag?: boolean;
}

Below is how the link prop is used. Part of the difficulty in setting the type is that, it’s used for both the html href attribute and react-router-dom Link.

   if (!useAnchorTag) return <Link to={link}>{text}</Link>;
    return <a. href={link}>
      {text}
    </a>;

The current type of the link prop is causing the following errors for the a href attribute.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Type 'string | { pathname: string; state: { from: string; }; hash: string; }' is not assignable to type 'string | undefined'.

I found that undefined is being derived from the property itself

index.d.ts(2012, 9): The expected type comes from property 'href' which is declared here on type 'DetailedHTMLProps<AnchorHTMLAttributes<HTMLAnchorElement>, HTMLAnchorElement>
(JSX attribute) AnchorHTMLAttributes<HTMLAnchorElement>.href?: string | undefined

>Solution :

The href expects a string (or undefined) but your type says it’s either string or your "path" object. So that is not compatible. If you want to have a type that works for both href and Link that type must only be string, because that is the only type that is accepted by both properties.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading