DEV Community

Cover image for A Next.js 15 Dynamic Route Helper Type
Andrew Ross
Andrew Ross

Posted on • Edited on

A Next.js 15 Dynamic Route Helper Type

The types to use

export type InferGSPRTWorkup<T> =
  T extends Promise<readonly (infer U)[] | (infer U)[]> ? U : T;


export type InferGSPRT<T extends (...args: any) => any> = {
  params: Promise<InferGSPRTWorkup<ReturnType<T>>>;
};

Enter fullscreen mode Exit fullscreen mode

InferGSPRTWorkup<T>

export type InferGSPRTWorkup<T> =
  T extends Promise<readonly (infer U)[] | (infer U)[]> ? U : T;
Enter fullscreen mode Exit fullscreen mode

InferGSPRT<T>

export type InferGSPRT<T extends (...args: any) => any> = {
  params: Promise<InferGSPRTWorkup<ReturnType<T>>>;
};
Enter fullscreen mode Exit fullscreen mode

Usage

export default async function Example({ params }: InferGSPRT<typeof generateStaticParams>) {
   const { slug } = await params;
   // rest...
};
Enter fullscreen mode Exit fullscreen mode

Summary

Copy-paste the two types defined initially into a file in your code base. Use InferGSPRT within the page file of dynamic routes to infer the params object returned by generateStaticParams effortlessly.


Nextjs versions 13 & 14

Remove the outer Promise in the InferGSPRT type definition. The params object is synchronously resolved by the exported default function prior to version 15.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)