typescript - 如何为 Prisma 选择属性键入变量

我正在寻找一种方法来定义 Prisma select 语句,然后在多个地方使用它。例如:

const userSelect: Prisma.UserSelect = {
    id: true,
    name: true,
}

const user = await prisma.user.findUnique({
    where: { id: 1 },
    select: userSelect
})

const posts = await prisma.post.findMany({
    where: { authorId: 1 },
    select: {
        id: true,
        user: {
            select: userSelect
        }
    }
})

但是,这无法正常工作。在查询中使用 userSelect 时,查询知道 userSelect 是预期类型 Prisma.UserSelect,但他们不知道哪些字段具有实际上被选中了。这最终将 userposts.user 都键入为 {}

另一种方法是像这样编写 userSelect:

const userSelect = {
    id: true,
    name: true,
} as const;

在查询中有效并正确键入查询结果。但是,现在我在 userSelect 的定义中失去了类型安全和自动完成功能。

有人能想出一种解决方案,既能在查询选择属性、查询结果中正常工作,又能在选择对象的定义中实现类型安全吗?

最佳答案

Prisma 刚刚发布了一篇涵盖这个确切主题的文章。 https://www.prisma.io/blog/satisfies-operator-ur8ys8ccq7zb

引用文章:

One of the most common use cases for the satisfies operator with Prisma is to infer the return type of a specific query method like a findUnique — including only the selected fields of a model and its relations.

import { Prisma } from "@prisma/client";

// Create a strongly typed `PostSelect` object with `satisfies`
const postSelect = {
  title: true,
  createdAt: true,
  author: {
    name: true,
    email: true,
  },
} satisfies Prisma.PostSelect;

// Infer the resulting payload type
type MyPostPayload = Prisma.PostGetPayload<{ select: typeof postSelect }>;

// The result type is equivalent to `MyPostPayload | null`
const post = await prisma.post.findUnique({
  where: { id: 3 },
  select: postSelect,
});

https://stackoverflow.com/questions/74157774/

相关文章:

r - R中,如果有多个TRUE答案,选择第一个TRUE答案

javascript - 左侧条件分配

c# - ocelot api网关中的System.InvalidOperationExceptio

python - 将扁平化列表转换为字典列表

python - 确定谁拥有超过 80% 的给定发货人

c# - .NET 6 将参数检查替换为 ArgumentNullException.ThrowIf

javascript - 在 Javascript 中没有双 for 循环的情况下用对象数组中的 0

r - 选定列乘以给定向量

haskell - 如何声明一个参数可以是 (Int, Int) 或 Maybe (Int, Int

r - 如何合并两个数据框并提取列的唯一组合?