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

如何在Prisma模型中将属性类型设为枚举数组?

解决Prisma模型中枚举数组类型含undefined的问题

要让foo的类型固定为Tags枚举的数组、避免出现"TagA"[] | undefined,分两种场景处理:

场景1:创建实例时必须传入foo值

直接声明字段类型为Tags[]即可,只要创建时必填该字段,生成的TS类型就会是Tags[]而非可选:

model ExampleModel {
  id   String @id @default(auto()) @map("_id") @db.ObjectId
  name String @unique
  foo  Tags[] // 必填枚举数组
}

enum Tags {
  TagA
  TagB
  TagC
}

场景2:创建时可省略foo,默认空数组

给字段添加@default([])设置默认空数组,这样即使创建时不传foo,它也会自动初始化为空数组,TS类型固定为Tags[]:

model ExampleModel {
  id   String @id @default(auto()) @map("_id") @db.ObjectId
  name String @unique
  foo  Tags[] @default([]) // 默认空数组的枚举数组
}

enum Tags {
  TagA
  TagB
  TagC
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 02:04:51