使用Prisma和TypeScript遍历MySQL JSON字段时遇类型错误
解决Prisma处理MySQL JSON数组时的"Property 'map' does not exist on type 'never'"错误
问题原因
- 你在
if代码块内重新声明了const cateringObject,覆盖了外部的同名变量,导致外部的cateringObject始终保持初始值null,TypeScript无法推断它的数组类型,最终出现never类型错误。 - 直接断言为
Prisma.JsonArray(本质是unknown[])无法让TypeScript识别你自定义的CateringItem结构,后续遍历访问item.productName也会存在类型隐患。
解决方案
- 移除
if块内的const关键字,直接给外部的cateringObject赋值 - 将JSON数组断言为你定义的
CateringItem[]类型,让TypeScript识别数组元素的结构
修改后的核心代码
数据获取与类型转换部分
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,直接赋值给外部变量,并断言为CateringItem[] cateringObject = Booking.catering as CateringItem[]; }
遍历渲染部分
<ul> {cateringObject?.map((item) => <li>{item.productName}</li>)} </ul>
可选优化:自定义类型守卫
如果想提升类型安全性,避免直接断言带来的风险,可以添加类型守卫函数:
function isCateringItemArray(value: unknown): value is CateringItem[] { if (!Array.isArray(value)) return false; return value.every(item => typeof item === 'object' && item !== null && 'quantity' in item && typeof item.quantity === 'number' && 'productName' in item && typeof item.productName === 'string' && 'productPrice' in item && typeof item.productPrice === 'number' ); } // 使用类型守卫替代类型断言 if (Booking?.catering && isCateringItemArray(Booking.catering)) { cateringObject = Booking.catering; }
内容的提问来源于stack exchange,提问作者user10980228
相关产品推荐
相关产品推荐

