Trying to loop over mysql json field using prisma and typescript

Advertisements

I have a json field in mysql, and I am trying to loop over it.

I found that I should do this according to the Prisma docs:

  const Booking = await prisma.Booking.findUnique({
    where: { id: parseInt(params.id) },
  });

  let cateringObject: CateringItem[] | null = null;

  if (
    Booking?.catering &&
    typeof Booking?.catering === "object" &&
    Array.isArray(Booking?.catering)
  ) {
    const cateringObject = Booking?.catering as Prisma.JsonArray;
  }

I did try create this interface

interface CateringItem {
  quantity: number;
  productName: string;
  productPrice: number;
}

The error is when I try to loop over

          <ul>
            {cateringObject &&
              cateringObject.map((item) => <li>{item.productName}</li>)}
          </ul>

Property ‘map’ does not exist on type ‘never’.

>Solution :

 let cateringObject: CateringItem[] | null = null;
//
//
//
const cateringObject = Booking?.catering as Prisma.JsonArray;

Usually you cannot redeclare as a constant if you wish to use cateringObject outside the block. This might be what’s triggering the error as Typescript cannot infer the type of cateringObject.

Leave a ReplyCancel reply