如何获取包含关联关系的Prisma模型TypeScript类型?
获取Prisma关联查询结果的TypeScript类型
当你用Prisma查询包含关联的模型时,默认生成的Event类型只包含基础字段,不会带上关联属性。下面是两种靠谱的解决方法:
方法一:用Prisma内置的GetPayload工具类型
Prisma提供了Prisma.ModelNameGetPayload工具类型,可以根据你的查询配置生成对应的结果类型。比如你查询Event时要包含Owner关联,写法如下:
import { Prisma } from "@prisma/client"; // 直接定义包含Owner的查询配置,并生成对应的结果类型 type EventWithOwner = Prisma.EventGetPayload<{ include: { Owner: true }; }>; // 在组件Props中使用这个类型 type EventDetailsProps = { event: EventWithOwner; };
如果你的关联配置更复杂(比如嵌套多层关联),也可以直接在include里写完整的结构,GetPayload会自动生成对应的嵌套类型。
方法二:从查询函数返回值推断类型
如果已经有现成的查询函数,可以直接从函数的返回值里提取类型,不用手动写配置:
import { prisma } from "../your-prisma-client-path"; // 定义查询函数 async function fetchEventWithOwner(eventId: string) { return prisma.event.findUnique({ where: { id: eventId }, include: { Owner: true }, }); } // 提取函数返回值的类型(Awaited用来处理Promise) type EventWithOwner = Awaited<ReturnType<typeof fetchEventWithOwner>>; // 组件Props类型 type EventDetailsProps = { event: EventWithOwner; };
为什么之前的写法不生效?
- 默认的
Event类型是Prisma生成的基础模型类型,只包含表本身的字段,不会包含任何关联数据。 Prisma.EventInclude是用来配置查询时要包含哪些关联的类型,不是查询结果的类型,所以不能直接用来定义组件Props。
内容的提问来源于stack exchange,提问作者Gerrit
相关产品推荐
相关产品推荐

