【问题标题】:Add an interface to possible null value with Typescript使用 Typescript 为可能的 null 值添加接口
【发布时间】:2019-10-19 16:39:22
【问题描述】:

我正在使用 Express、Typescript 和 MongoDB Node.JS 驱动程序来开发我的 API;目前我遇到了 findOne 方法的问题,因为返回了一个承诺,但是,只有第一个文档的对象与查询匹配,或者如果出现问题,则返回一个简单的 null。

所以我试图在 Promise 得到解决时将该对象放入一个变量中,所以我有这样的东西:

let user = await db.collection('collectionName').findOne({ email: "example@stack.com" });

所以当我尝试为我的变量设置接口时,我收到下一个错误:

let user: UserStructure = await db.collection('collectionName').findOne({ email: "example@stack.com" }); 

// Type 'object | null' is not assignable to type 'UserStructure'.
// Type 'null' is not assignable to type 'UserStructure'.

一些建议?

【问题讨论】:

  • let user: UserStructure | null = ...?

标签: node.js mongodb typescript express


【解决方案1】:

@shanon 是正确的。 TypeScript 关心可能为空/未定义的值,这进一步可能导致空引用错误。

您可以选择在tsconfig.json 中的compilerOptions 下设置"strictNullChecks":false

【讨论】:

  • 谢谢,我要试试,因为我不断收到 Object is possible 'null' 错误。
【解决方案2】:

这里发生的事情是 typescript 正在尽力保护您,mongodb 已将该函数标记为可能返回 null,但您的代码不能防止 null。

以 typescript 可以分析和更改变量类型以允许 null 的方式更改代码以防止 null 并且错误将消失。

let user: UserStructure | null = await db.collection('collectionName').findOne({ email: "example@stack.com" });
if(!user) return res.status(400).send("No user could be found")
// user will now be UserStructure after this early return. and not UserStrcuture | null

【讨论】:

  • 它部分工作,但现在当我尝试访问对象的一个​​属性(例如 user._id)时,我收到下一个错误:对象可能为“空”。
  • 使用“if”检查错误将消失,因为 typescript 可以理解您已针对 null 进行了保护。 (如果用户为空则返回)。这将缩小类型,并在 if 检查之后将所有代码中的 null 去掉。
猜你喜欢
  • 2018-08-28
  • 2020-01-07
  • 2021-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-17
  • 2021-06-29
  • 1970-01-01
相关资源
最近更新 更多