Search code examples
next.jsreact-typescriptemotion

How to get NextJS Url type for HOC?


I'm constructing a Link within a component, and need to accept href as a prop. However, I'm having issues defining that type.

import React from "react;
import Link, { LinkProps } from "next/link";

type MyComponentProps = {
  href: Pick<LinkProps, "href">
}

export const MyComponent: React.FC<MyComponentProps> = ({ href }) => (
  <Link href={href}>
    <a>Some Link Text</a>
  </Link>
);

I'm getting a type error:

  Type 'Pick<InternalLinkProps, "href">' is not assignable to type 'UrlObject'.
    Types of property 'href' are incompatible.
      Type 'Url' is not assignable to type 'string | null | undefined'.
        Type 'UrlObject' is not assignable to type 'string'.ts(2322)
link.d.ts(6, 5): The expected type comes from property 'href' which is declared here on type 'IntrinsicAttributes & { css?: Interpolation<Theme>; } & Omit<AnchorHTMLAttributes<HTMLAnchorElement>, keyof InternalLinkProps> & InternalLinkProps & { ...; } & RefAttributes<...>'

How do I define the type for href in this Components props?

I saw this resource, but it didnt help


Solution

  • Pick won't work here, since Pick<LinkProps, "href"> would return an object that contains the link property, rather than just the value

    I think you just want LinkProps["href"] but you can also use these:

    type ComponentProps = Pick<LinkProps, "href">
    type ComponentProps = Pick<LinkProps, "href"> & { ... otherProps}