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

Prisma使用指南:如何从生成的Typescript类型中排除指定属性

补充提醒:在TS类型定义中隐藏字段存在隐性风险:开发阶段智能提示不会显示这些字段,但包含「隐藏」字段的完整对象可能会被意外放入响应返回,存在敏感数据泄露的隐患。

推荐方案(查询时直接排除字段,更安全简洁)

Prisma原生支持嵌套关系的字段选择,不需要单独定义子模型的validator,也不需要手动合并类型,直接在include的posts配置项中添加select规则即可:

import { Prisma } from '@prisma/client'

const userWithPosts = Prisma.validator<Prisma.UserArgs>()({
  include: { 
    posts: {
      select: {
        id: true, 
        title: true, 
        published: true, 
        authorId: true
      }
    } 
  },
})

// 直接使用自动生成的Payload类型,无需额外Omit操作
type UserWithPosts = Prisma.UserGetPayload<typeof userWithPosts>

该方案不仅会自动推导正确的TS类型,实际查询数据库时也不会拉取createdAt字段,从根源避免敏感字段意外泄露的问题。

备选方案(仅类型层面排除字段)

如果你确实需要在查询时拉取全量Post字段,只需要在类型层面排除指定字段,可以直接对嵌套类型做Omit处理:

import { Prisma } from '@prisma/client'

const userWithPosts = Prisma.validator<Prisma.UserArgs>()({
  include: { posts: true },
})

type UserWithPosts = Prisma.UserGetPayload<typeof userWithPosts> & {
  posts: Omit<Prisma.PostGetPayload<{}>, 'createdAt'>[]
}

注意使用该方案时需额外警惕前面提到的隐藏字段泄露风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 06:24:03