如何在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
相关产品推荐
相关产品推荐

