node.js - 使用 Typescript 添加一个可能为空值的接口(interface)

标签 node.js mongodb typescript express

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

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

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

因此,当我尝试为变量设置接口(interface)时,我收到下一个错误:

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'.

有什么建议吗?

最佳答案

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

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

关于node.js - 使用 Typescript 添加一个可能为空值的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58461714/

相关文章:

javascript - 在 node.js 中扩展类的不同方式

javascript - Angular 应用程序转移到版本 6 错误 : 'Global is not defined'

mongodb - pymongo 无法检索文件

arrays - Angular通过Id从数组中获取对象

Typescript + Electron 资源图

node.js - Node js app.configure 不是一个函数

javascript - MongoDB - 使用 $set 更新子文档

c# - 从 MongoDB 查询嵌套对象(第 2 部分)

angular - 使用带有 RxJS 的 Angular 5 和过滤器观察数组

node.js - 如何在 "real world"时间内每 n 毫秒调用一个函数?