node.js - 使用 Typescript 为可能的 null 值添加一个接口
问题描述
我正在使用 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'.
一些忠告?
解决方案
@shanon 是正确的。TypeScript 关心可能为空/未定义的值,这进一步可能导致空引用错误。
您可以选择"strictNullChecks":false
在您的tsconfig.json
下设置compilerOptions
推荐阅读
- ruby-on-rails - 如何在 Rails 中公开动态 url
- c - 有没有什么情况下 IO 函数永远不会失败?
- kubernetes - kubectl 错误:无法添加密钥 dashboard.yaml,该名称的另一个密钥已存在
- 3d - 根据其在 Godot 中的旋转变换空间节点
- java - 如何在 GSON 反序列化期间忽略空字符串
- r - R Shiny中的相互依赖的过滤器级联 - updatePickerInput
- java - 如何使用 Room 创建多个表?
- swift - 进入后台后如何保持在打开的 WKWebView 上创建的 WebSocket 连接一段时间
- django - 如何在 Django 模板的内循环部分访问外循环上下文值
- c# - WCF 服务 SSRS 在我的浏览器上通过 URL 工作,但在 WCF 客户端上不工作?