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

TypeScript编写Prisma工具函数:正确实现类型推断

解决Prisma工具函数的类型推断问题

要让工具函数能自动根据传入的prismaArgs推断prismaData的类型,无需依赖类型断言或any,可以利用Prisma提供的内置类型工具实现类型安全的动态推断。以下是最佳实践方案:

完整实现代码

import type { Prisma, Session } from '@prisma/client'

// 假设getSessionId为已定义的全局函数
declare function getSessionId(): string;

function utilityFunction<
  // 定义允许传入的参数类型:移除findUnique必填的where,补充可选的部分where条件
  TArgs extends Omit<Prisma.SessionFindUniqueArgs, 'where'> & { where?: Partial<Prisma.SessionWhereUniqueInput> },
  R,
  A extends unknown[]
>(
  prismaArgs: TArgs,
  fn: (
    // 动态推断findUnique的返回类型,基于传入的参数和最终合并后的where条件
    prismaData: Prisma.GetFindUniqueResult<Session, TArgs & { where: Prisma.SessionWhereUniqueInput }>,
    ...args: A
  ) => Promise<R>
) {
  return async function(...args: A) {
    const prismaData = await prisma.session.findUnique({
      ...prismaArgs,
      where: {
        ...prismaArgs.where,
        sessionId: getSessionId()
      } satisfies Prisma.SessionWhereUniqueInput // 确保合并后的where符合唯一查询规范
    })
    return await fn(prismaData, ...args)
  }
}

// 使用示例
const fn = utilityFunction(
  { 
    include: {
      user: { select: { userId: true } } // 修正Prisma语法:include内需指定select/include
    }
  },
  async (prismaData, arg1, arg2) => {
    // prismaData会自动推断为 Session & { user: { userId: string } }
    console.log(prismaData.user?.userId)
    return 'processed result'
  }
)

// 调用时参数类型自动匹配
fn('exampleArg1', 'exampleArg2')

关键实现要点

  • 类型约束:通过Omit<Prisma.SessionFindUniqueArgs, 'where'>移除findUnique原本必填的where字段,再补充可选的partial where,允许用户传入部分查询条件,同时保留include/select等其他参数的类型约束。
  • 动态类型推断:使用Prisma内置的GetFindUniqueResult工具类型,根据传入的TArgs和最终合并后的完整where条件,自动推导findUnique的返回类型,完全替代any或类型断言。
  • 类型安全校验:用satisfies关键字确保合并后的where符合SessionWhereUniqueInput类型,避免非法查询条件导致的运行时错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 22:47:05