skip to Main Content

I want to add a type for my dynamic route that I can replace with type "any" in code bellow written with Typescript .

export default async function DetailProduct({ params }: any) {
    const { imageAddress, title, price } = await getProductByID(params.id);

    return ...
}

Does nextjs have a type for it ? I use nextjs14

2

Answers


  1. NextJS does not have a type for it. But hey, you can define the type according to your usage of keys right. If you are simply using the string id from params, just define the types as below:

    export default async function DetailProduct({ params }:{ params : { id : string } } ) {
        const { imageAddress, title, price } = await getProductByID(params.id);
    
        return ...
    }
    
    

    Example from docs

    Login or Signup to reply.
  2. You define your own types either at the call or you can create an definition

    You don’t need the await part you can just extract the id from the param object.

    export default function Product({ params }: { params: { id: string } }) {
    const { id } = params;
    return (
        <>
            <div>Product ID: {id}</div>
        </>
    )}
    
    interface IProduct = {
      imageAddress: string; 
      title: string;
      price: number;
    }
    
    
    export default function Product({ params }: { params: IProduct }) {
    ...
    

    Source https://raynoppe.com/snippets/nextjs-app-router/app-structure-in-next-js/page-component/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search