Prisma中选择特定字段不起作用

3
我想选择特定的字段。
return this.prisma.user.findFirst({
  where: {
    password_hash: createHash('md5')
      .update(`${userId.id}test`)
      .digest('hex'),
  },
  select: {
    name: true,
    email: true,
  },
});

但是我遇到了这个打字错误

类型“{ name: string; email: string; }”缺少类型“User”的以下属性:id、password_hash

下面是用户的类型定义

export type User = {
  id: number
  name: string
  email: string
  password_hash: string
}

1
函数的预期返回类型是什么?由于您的查询中有 select,返回表达式的类型为 Promise<{ name: string, email: string } | null>。这符合您的预期吗? - Nicholas Weston
1个回答

1

您在调用函数时返回了错误的类型。如果添加一个 select 子句,返回结果将被缩减为所选属性,而您假装从包装函数中返回完整的 User

// The full user:
type User = {
  id: number
  name: string
  email: string
  password_hash: string
}

// Here you pretend to return a full user:
function getUser(userId): Promise<User | null> {
  return this.prisma.user.findFirst({
    where: {
      password_hash: createHash('md5')
        .update(`${userId.id}test`)
        .digest('hex'),
    },
    select: { // Here you remove some properties from the user:
      name: true,
      email: true,
    },
  });
}

你可以通过改变返回类型来修复它:

function getUser(userId): Promise<{ name: string, email: string } | null> {
   ...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接