How do you properly type the props of a page component that receives dynamic route parameters?
Short answer
You define a type or interface describing the shape of the params object your page expects, matching the dynamic segments in your folder structure, and use it to type the props parameter of your page component, letting TypeScript catch mistakes if you try to access a parameter…
Advertisement
AModel answer
You define a type or interface describing the shape of the params object your page expects, matching the dynamic segments in your folder structure, and use it to type the props parameter of your page component, letting TypeScript catch mistakes if you try to access a parameter that does not exist.
type PageProps = {
params: Promise<{ id: string }>;
};
export default async function ProductPage({ params }: PageProps) {
const { id } = await params;
return <h1>Product {id}</h1>;
}Real-world example
A product page properly types its params object, letting TypeScript immediately catch a typo if a developer accidentally tries to access a parameter name that does not match the actual dynamic route segment.
Likely follow-ups
- Why is the params object typed as a Promise in recent versions of Next.js?
- How do you type searchParams for a page that reads query string values?
Related topics