Quick tips when working with Prisma. Say you have a model with a Json type attribute that you want to type, because the default types don't contain information about the keys and values inside the json object we'll need to manually type them.
Say this is our User model with the extendedProfile attribute appended at the bottom:
model User {
id Int @default(autoincrement()) @id
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
email String @unique
hashedPassword String?
role String @default("user")
sessions Session[]
extendedProfile Json?
}
We can create a types.ts file and export an ExtendedUser type.
export type ExtendedUser = User & {
extendedProfile: {
firstName: string
lastName: string
}
}
Prisma also comes with some useful methods. Let’s say we’re working with a model that has a relation reference with another model.
For example, if the User model has a one-to-many relation with an Order model.
model User {
id Int @default(autoincrement()) @id
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
email String @unique
hashedPassword String?
role String @default("user")
sessions Session[]
extendedProfile Json?
orders Order[]
}
model Order {
id Int @default(autoincrement()) @id
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id])
userId Int
}
Inside types.ts we can import Prisma and use the GetPayload method it provides. So in our case our ExtendedUser type will look like this:
import { Prisma } from '@prisma/client'
export type ExtendedUser = Prisma.UserGetPayload<{ include: { order: true } }> & {
extendedProfile: {
firstName: string
lastName: string
}
}
GetPayload will always start with the model name. In our case UserGetPayload
