Home > OS >  How to properly set prop type in React using Typescript
How to properly set prop type in React using Typescript

Time:08-25

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.

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

CodePudding user response:

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.

  • Related