针对模型类型的局部结构进行操作
使用 Prisma Client 时,Prisma schema 中的每个模型都会被转换为一个专门的 TypeScript 类型。例如,假设您有以下 User
和 Post
模型
model User {
id Int @id
email String @unique
name String?
posts Post[]
}
model Post {
id Int @id
author User @relation(fields: [userId], references: [id])
title String
published Boolean @default(false)
userId Int
}
从这个 schema 生成的 Prisma Client 代码包含了 User
类型的这个表示
export type User = {
id: string
email: string
name: string | null
}
问题:使用生成的模型类型的变体
描述
在某些场景下,您可能需要生成的 User
类型的变体。例如,当您有一个函数期望接收一个带有 posts
关系的 User
模型实例时。或者当您只需要在应用代码中传递 User
模型的 email
和 name
字段的类型时。
解决方案
作为解决方案,您可以使用 Prisma Client 的辅助类型来定制生成的模型类型。
User
类型只包含模型的标量字段,但不包含任何关系。这是因为在 Prisma Client 查询中,关系默认不包含在内。
然而,有时拥有一个包含关系的可用类型会很有用(例如,您通过使用include
的 API 调用获得的类型)。类似地,另一个有用的场景是拥有一个只包含模型标量字段子集的可用类型(例如,您通过使用select
的 API 调用获得的类型)。
实现这一目标的一种方法是在您的应用代码中手动定义这些类型
// 1: Define a type that includes the relation to `Post`
type UserWithPosts = {
id: string
email: string
name: string | null
posts: Post[]
}
// 2: Define a type that only contains a subset of the scalar fields
type UserPersonalData = {
email: string
name: string | null
}
虽然这当然可行,但这种方法增加了 Prisma schema 更改时的维护负担,因为您需要手动维护类型。一个更清晰的解决方案是使用 Prisma Client 在 Prisma
命名空间下生成和暴露的 UserGetPayload
类型,并结合validator
。
以下示例使用 Prisma.validator
创建了两个类型安全的对象,然后使用 Prisma.UserGetPayload
工具函数创建了一个可用于返回所有用户及其帖子的类型。
import { Prisma } from '@prisma/client'
// 1: Define a type that includes the relation to `Post`
const userWithPosts = Prisma.validator<Prisma.UserDefaultArgs>()({
include: { posts: true },
})
// 2: Define a type that only contains a subset of the scalar fields
const userPersonalData = Prisma.validator<Prisma.UserDefaultArgs>()({
select: { email: true, name: true },
})
// 3: This type will include a user and all their posts
type UserWithPosts = Prisma.UserGetPayload<typeof userWithPosts>
后一种方法的主要优点是
- 更清晰的方法,因为它利用了 Prisma Client 生成的类型
- schema 更改时减少维护负担并提高类型安全
问题:获取函数的返回类型
描述
当您对模型执行 select
或 include
操作并将这些变体从函数返回时,很难获得返回类型,例如
// Function definition that returns a partial structure
async function getUsersWithPosts() {
const users = await prisma.user.findMany({ include: { posts: true } })
return users
}
从上面的代码片段中提取表示“带有帖子的用户”的类型需要一些高级的 TypeScript 用法
// Function definition that returns a partial structure
async function getUsersWithPosts() {
const users = await prisma.user.findMany({ include: { posts: true } })
return users
}
// Extract `UsersWithPosts` type with
type ThenArg<T> = T extends PromiseLike<infer U> ? U : T
type UsersWithPosts = ThenArg<ReturnType<typeof getUsersWithPosts>>
// run inside `async` function
const usersWithPosts: UsersWithPosts = await getUsersWithPosts()
解决方案
使用 Prisma
命名空间暴露的 PromiseReturnType
,您可以更优雅地解决这个问题
import { Prisma } from '@prisma/client'
type UsersWithPosts = Prisma.PromiseReturnType<typeof getUsersWithPosts>