Add type to a Prisma JSON fields
April 16, 2024
Using the external package prisma-json-types-generator you can type JSON fields in Prisma.
-
Install and configure the package adding the json provider.
generator client { provider = "prisma-client-js" } /// Always after the prisma-client-js generator generator json { provider = "prisma-json-types-generator" } -
Then update your model adding the type by using abstract syntax tree comments.
model User { id Int @id /// [UserAddress] <- Your type here address Json } -
Finally declare the PrismaJson namespace adding your type.
declare global { namespace PrismaJson { interface UserAddress { city: string street: string postalCode: number } } }Important: Make sure the file has the extension
.d.ts. Otherwise your types may not work.
Every time that you changed your declarations types, you need to migrate the scheme to implement it.
For more information visit Prisma documentation and the prisma-json-types-generator package.