我正在使用 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/