【问题标题】:I cant remove the error "Type 'User | null' is not assignable to type 'User'. Type 'null' is not assignable to type 'User'"我无法删除错误“类型'用户| null'不可分配给类型'用户'。类型'null'不可分配给类型'用户'”
【发布时间】:2020-07-13 19:45:02
【问题描述】:
export interface User {
  id: string
  name: string
  bio: string
  public_repos: string
  public_gists: string
}
async function getPrismaUser(
  ctx: Context,
  githubUserId: string,
): Promise<User> {
  return await ctx.prisma.user.findOne({ where: { githubUserId } })
}

我尝试在我的 return 语句中添加非空断言检查,但错误并没有消失。我唯一的解决方案是 "strict": false in tsconfig.json 吗?

【问题讨论】:

  • 该错误在哪里显示?另外,你的非空检查在哪里?
  • findOne 可能会返回 null。如果您为此添加检查并在函数中抛出异常null,则错误将消失

标签: typescript prisma


【解决方案1】:

findOne() 的返回类型是User | null(有几个条件,见下文)。该联合类型与您的函数getPrismaUser() 的返回类型不匹配,即User

要修复您的错误,请将getPrismaUser() 的返回类型更改为User | null

findOne 返回一个普通的旧 JavaScript 对象或 null。

findOne API 调用返回的对象类型取决于 关于是否使用 select 和 include 选项。

如果您不使用这两个选项,则返回类型将对应 为模型生成的 TypeScript 类型。

来自Prisma docs

【讨论】:

  • 虽然这不是 OP 所要求的,但我要补充一点,他们应该在某处处理 null 返回类型的可能性。
猜你喜欢
  • 2023-01-25
  • 1970-01-01
  • 1970-01-01
  • 2018-07-07
  • 1970-01-01
  • 2022-08-23
  • 1970-01-01
  • 2018-02-02
  • 2021-06-17
相关资源
最近更新 更多