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.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay