Reach / Questions

Issue typing usage of Link with TypeScript

Issue typing usage of Link with TypeScript

Reach/Questions · November 30, 2018 at 10:33am

Issue typing usage of Link with TypeScript

Reach / Questions · November 30, 2018 at 10:33am
Hi, I'm having some issues with typing usage of Link with TypeScript. I'm pretty new to TypeScript so I'm probably doing something wrong, but I really can't figure out if it's an actual problem with the type definitions of reach router or not.
I've created a repo on github to reproduce the issue:
https://github.com/artisologic/reach-router-ts-issue
Any help would be highly appreciated!
Thanks!

December 1, 2018 at 11:02pm

Hi,

I don't understand why you wrap the `Link` around the `MyLink` function since all you are doing is returning it without adding any custom props :)

But let's say you wanted to pass some additional props, you could do it like this:

type Props = {
  label: string
}

function MyLink(props: Props & LinkProps<{}>) {
  return <Link>{props.label}</Link>
}

Later on call site:

<MyLink label="ok" to="/"/>

Edited
  • reply
  • like

Hi @alxl, thanks for your reply. Yes the example is contrived, that's just to synthesise the issue I'm having. In reality it's rather a NavLink implementation which adds a className if the link is active (current route). Your example makes sense to me, but it doesn't solve the issue I'm having. The compiler still complains about the same thing exactly. Did you try on your side?

  • reply
  • like

I see, you should check the docs here: https://reach.tech/router/example/active-links

But for the gist of it:

type Props = {
  label: string
  activeClassName: string
}

function MyLink(props: Props & LinkProps<{}>) {
  return (
    <Link
      getProps={linkProps => ({
        className: linkProps.isCurrent && props.activeClassName,
      })}
    >
      {props.label}
    </Link>
  )
}

later on call site:

<MyLink activeClassName="bar" label="ok" to="/" />

Edited
  • reply
  • like

Log in or sign up to chat