You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义服务函数中的Prisma返回类型问题

问题描述

直接使用Prisma查询用户记录时,我们可以通过include指定要包含的关联关系,返回结果会正确包含对应关联字段:

const user = await prisma.user.findFirst({ where: { id: 'something' }, include: { profile: true } })

user.profile // 存在,类型提示正常

但将查询逻辑封装成自定义服务方法后,即便传入include参数,返回类型却不会包含所选的关联关系:

const findOne = (args: Prisma.UserFindFirstArgs) => {
  return client.user.findFirst(args);
};

const user = await findOne({ where: { id: 'something' }, include: { profile: true } })

user.profile // 不存在,类型提示报错

为什么自定义服务函数中Prisma的返回类型无法包含指定的关联关系?

原因分析

核心问题在于泛型推导丢失:

  • Prisma的findFirst是泛型方法,它会根据你传入的include/select参数动态推导返回类型,自动把关联字段加入返回结果的类型中。
  • 但你定义的findOne函数直接用Prisma.UserFindFirstArgs作为参数类型,这是findFirst的默认参数类型,没有保留泛型的动态推导能力。
  • 当你把args传入client.user.findFirst(args)时,TypeScript无法再识别args里的具体include配置,只能默认返回基础的User类型(不含任何关联字段)。
解决方案

让自定义函数也使用泛型,匹配PrismafindFirst方法的泛型参数,保留动态类型推导能力。修改后的代码如下:

import { Prisma, PrismaClient } from '@prisma/client';

const client = new PrismaClient();

// 通过泛型继承保留参数的动态类型信息
const findOne = <Args extends Prisma.UserFindFirstArgs>(args: Args) => {
  return client.user.findFirst(args);
};

// 此时调用时,返回类型会自动包含profile字段
const user = await findOne({ where: { id: 'something' }, include: { profile: true } })

user.profile // 存在,类型提示正常

这样修改后,自定义函数的返回类型会和直接调用prisma.user.findFirst时完全一致,根据你传入的include/select参数动态生成包含关联字段的类型。

内容的提问来源于stack exchange,提问作者Salim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 09:12:08