astronomy-club-at-nitic / nitic-astronomy

The website of Astronomy Club at NITIC.
https://nitic-astronomy-website.vercel.app
MIT License
2 stars 0 forks source link

`<Link>`が`next/link`用の型ジェネリクスを受け取れるようにする #171

Closed ReoHakase closed 1 year ago

ReoHakase commented 1 year ago

修正したいこと

next/linktypedRoutesを有効化している場合、型ジェネリクスをもとに動的パスが正しいものかどうかを判定する。 そのため、<Link>next/link用の型ジェネリクスを受け取らずunknownが渡されてしまう現状では、動的パスの推論ができない。

  type StaticRoutes = 
    | `/`
    | `/api/ogimage`
    | `/article`
    | `/member`
    | `/tag`
  type DynamicRoutes<T extends string = string> = 
    | `/article/${SafeSlug<T>}`
    | `/tag/${SafeSlug<T>}`

  type RouteImpl<T> = 
    | StaticRoutes
    | `${StaticRoutes}${SearchOrHash}`
    | (T extends `${DynamicRoutes<infer _>}${Suffix}` ? T : never)
export type LinkProps<T> = LinkRestProps & {
    /**
     * The path or URL to navigate to. This is the only required prop. It can also be an object.
     * @see https://nextjs.org/docs/api-reference/next/link
     */
    href: __next_route_internal_types__.RouteImpl<T> | UrlObject
  }

治し方

<Link>の型定義を書き換える。

// It is required to forward generics T to NextLinkProps in order to make DynamicRoute work.
// e.g. `/tag/[tagId]`
type LinkProps<T> =
  | NextLinkProps<T>
  | (ComponentPropsWithoutRef<'a'> & {
      external: true;
    });