I got this error in my code I am using Prisma Next js 14 and typescript I got this error while tyring to load my product details using product ID In bottom screenshot also have this error
Failed to compile.
./app/product/[productId]/page.tsx:13:40
Type error: Argument of type 'IParams' is not assignable to parameter of type 'IParams'.
Types of property 'productId' are incompatible.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
11 |
12 | const Product = async ({ params }: { params: IParams }) => {
> 13 | const product = await getProductById(params);
| ^
14 |
15 | if (!product)
16 | return <NullData title="OOPS! Product with given ID does not exist" />;
Error: Command "npm run build" exited with 1
this is my getProductById file
import prisma from '@/libs/prismadb';
interface IParams {
productId: string;
}
export default async function getProductById(params: IParams) {
try {
const { productId } = params;
const product = await prisma.product.findUnique({
where:{
id: productId
},
include:{
reviews:{
include:{
user: true
},
orderBy:{
createdDate: 'desc'
}
}
}
})
if(!product){
return null;
}
return product;
} catch (error: any) {
throw new Error(error);
}
}
And this is my page which this error got
import Container from "@/app/components/Container";
import ProductDetails from "./productDetails";
import ListRatings from "./ListRatings";
import getProductById from "@/actions/getProductById";
import NullData from "@/app/components/NullData";
interface IParams {
productId?: string;
}
const Product = async ({ params }: { params: IParams }) => {
const product = await getProductById(params);
if (!product)
return <NullData title="OOPS! Product with given ID does not exist" />;
return (
<div className="p-8">
<Container>
<ProductDetails product={product} />
<div className="flex flex-col mt-20 gap-4">
<div>Add Rating</div>
<ListRatings product={product} />
</div>
</Container>
</div>
);
};
export default Product;
Please help me to fix this error and this is my folder structure.
2
Answers
Well simply, you have 2 interfaces called IParams.
The one in the getProductById file has one attribute called productId which is a string.
The one in your component file also has one attribute called productId but this time it is a string or
undefined
(see the ‘?’).The problem basically is that you are giving a
string | undefined
where astring
is expected.What you can do is :
Also, why are you passing a IParams object to getProductById then extracting productId from it ? Why not passing
productId
directly ?You’ve defined two interfaces with the same name
IParams
.Both have one property
productId
, but in your second interface you definedproductId
as optional (used?
sign).Decide which type do you need (one with optional or the other) and the type error will be fixed.