首页 > 解决方案 > 使用 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'.

一些忠告?

标签: node.jsmongodbtypescriptexpress

解决方案


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

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


推荐阅读