简体   繁体   English

Typescript 在将 object 传递给 promise 中的 function 时给出 object 可能是 null 错误。然后

[英]Typescript gives object might be null error while passing object to function inside promise.then

The following is the code from a request controller function.以下是来自请求 controller function 的代码。

Objective I wanted to create different types of notifications depending upon the which paths are modified.目标我想根据修改的路径创建不同类型的通知。

let farmerToUpdate = await FarmerModel.findById(farmerId)
  if (!farmerToUpdate) throw new controllerError('Farmer you want to update is deleted', 422)

  // farmerToUpdate.set(Object.assign(farmerToUpdate, req.body))
  farmerToUpdate.set(req.body)

  let directModifiedPaths = farmerToUpdate.directModifiedPaths()
  const updatedFarmer = await farmerToUpdate.save()

  if (directModifiedPaths.includes('farmerCode') || directModifiedPaths.includes('centreCode')) {
    // farmerToUpdate is original document and updatedFarmer is document after updating
    createNotification(farmerToUpdate, updatedFarmer, ['farmerCode', 'lakshmiCentreCode'], true, 'Codes Updated').then(
      function () {
        directModifiedPaths = directModifiedPaths.filter(d => d !== 'farmerCode' && d !== 'lakshmiCentreCode')
        if (directModifiedPaths.length) {
          createNotification(farmerToUpdate, updatedFarmer, directModifiedPaths, false, 'Plain').then(res => {})
        }
      },
    )
  }

After creating notification of one type when I try to pass same first argument farmerToUpdate to the createNotification function I get following error当我尝试将相同的第一个参数farmerToUpdate传递给createNotification function 时创建一种类型的通知后,出现以下错误

Argument of type '(Document<unknown, any, Farmer> & Farmer & { _id: ObjectId; }) | '(Document<unknown, any, Farmer> & Farmer & { _id: ObjectId; }) | 类型的参数null' is not assignable to parameter of type 'Document<unknown, any, Farmer> & Farmer & { _id: ObjectId; null' 不可分配给 'Document<unknown, any, Farmer> & Farmer & { _id: ObjectId; 类型的参数} & { notificationId?: number | } & { notificationId?: 数字 | undefined;不明确的; }'. }'。 Type 'null' is not assignable to type 'Document<unknown, any, Farmer> & Farmer & { _id: ObjectId;类型 'null' 不可分配给类型 'Document<unknown, any, Farmer> & Farmer & { _id: ObjectId; } & { notificationId?: number | } & { notificationId?: 数字 | undefined;不明确的; }'. }'。 Type 'null' is not assignable to type 'Document<unknown, any, Farmer>'.类型“null”不可分配给类型“Document<unknown, any, Farmer>”。

If I add check for a valid farmerToUpdate it works fine -如果我添加检查有效的farmerToUpdate它工作正常 -

farmerToUpdate && createNotification(farmerToUpdate, updatedFarmer, directModifiedPaths, false, 'Plain').then(res => {})

I wonder why it not gives the same error for second parameter or third???我想知道为什么它不为第二个参数或第三个参数给出相同的错误???

The type of farmerToUpdate is nullable, but if (.farmerToUpdate) throw... makes it non-nullable anymore afterward in the same scope or any descendant scopes. farmerToUpdate的类型可以为 null,但if (.farmerToUpdate) throw...使其在相同的 scope 或任何后代范围内不再为 null。 ( https://www.typescriptlang.org/docs/handbook/2/narrowing.html ) ( https://www.typescriptlang.org/docs/handbook/2/narrowing.html )

But the nested function has it's own scope, and in it the farmerToUpdate 's type is still nullable.但是嵌套的 function 有它自己的 scope,其中farmerToUpdate的类型仍然可以为空。

Ideally, it's maybe possible for the compiler to determine that farmerToUpdate will actually never be null in the nested function, but it is more complex and the compiler just doesn't support that I think.理想情况下,编译器可能会确定嵌套的 function 中的farmerToUpdate实际上永远不会是 null,但它更复杂,我认为编译器不支持。

update:更新:

the return value of await FarmerModel.findById(farmerId) is nullable (in another word: it may return null), and therefor farmerToUpdate is nullable (in another word: it may be null). await FarmerModel.findById(farmerId)的返回值是可以为空的(换句话说:它可能返回null),因此farmerToUpdate是可以为空的(换句话说:它可能为null)。

But return values of farmerToUpdate.directModifiedPaths() and await farmerToUpdate.save() are non-nullable, and therefor updatedFarmer and directModifiedPaths are both non-nullable (in another word: they'll never be null).但是farmerToUpdate.directModifiedPaths()await farmerToUpdate.save()的返回值是不可为空的,因此updatedFarmerdirectModifiedPaths都是不可为空的(换句话说:它们永远不会为空)。

That's why the compiler only compains farmerToUpdate , but not updatedFarmer and directModifiedPaths .这就是编译器只兼容farmerToUpdate ,而不updatedFarmerdirectModifiedPaths的原因。

Actually farmerToUpdate.directModifiedPaths() should be farmerToUpdate..directModifiedPaths() .实际上farmerToUpdate.directModifiedPaths()应该是farmerToUpdate..directModifiedPaths() That's because the type of farmerToUpdate may be null, but we know it'll never be null in that context, therefor we can treat it as non-nullable.这是因为farmerToUpdate的类型可能是 null,但我们知道在这种情况下它永远不会是 null,因此我们可以将其视为不可空。 The compiler can do that deduction automatically, so we can eliminate the exclamation mark without error.编译器可以自动进行推导,所以我们可以无误地消除感叹号。

TypeScript型'承诺<void | object> ' 不可分配给类型 'Promise<object> ' 在 Promise.then()<div id="text_translate"><p> 我目前正在尝试以 base64 格式实现缓存文档的服务。 我希望这个服务从 sessionStorage 中获取文档,如果 sessionStorage 中没有文档,则从 IRequestService 中获取它,然后将其保存到 sessionStorage。 我尝试了这种方法,但出现类型错误</p><pre>Type 'Promise&lt;void | GetDocumentResult&gt;' is not assignable to type 'Promise&lt;GetDocumentResult&gt;'.</pre><p> 代码如下所示:</p><pre> getDocument(requestId: string, documentId: DocumentID, requestService: IRequestService): Promise&lt;GetDocumentResult&gt; { if (this.storageKey in sessionStorage) { const documentsMap: Map&lt;DocumentID, GetDocumentResult&gt; = new Map(JSON.parse(sessionStorage.getItem(this.storageKey).)) if (documentsMap.get(documentId).== undefined) { return new Promise(resolve =&gt; resolve(documentsMap,get(documentId).)) } } return requestService.getDocument(requestId, documentId) .then(value =&gt; {this.setDocument(documentId, value)}) }</pre><p> 我期待 Promise&lt;GetDocumentResult&gt;.then 的返回类型是 Promise&lt;GetDocumentResult&gt;,但由于某种我不明白的原因,它是 Promise&lt;void | 获取文档结果&gt;</p><p> 有人知道为什么会这样吗?</p><p> 谢谢</p></div></object></void> - TypeScript Type 'Promise<void | Object>' is not assignable to type 'Promise<Object>' on Promise.then()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在“ Promise.then()”中返回带有“ then”功能的对象 - Return an object with a “then” function within “Promise.then()” Wasm: Uncaught (in promise) TypeError: Import #0 module=&quot;env&quot; error: module is not an object or function Promise.then (async) (anonymous) @ (index):9 - Wasm: Uncaught (in promise) TypeError: Import #0 module="env" error: module is not an object or function Promise.then (async) (anonymous) @ (index):9 TypeScript在Promise.then中编译错误 - Typescript compile error in promise.then TypeScript型'承诺<void | object> ' 不可分配给类型 'Promise<object> ' 在 Promise.then()<div id="text_translate"><p> 我目前正在尝试以 base64 格式实现缓存文档的服务。 我希望这个服务从 sessionStorage 中获取文档,如果 sessionStorage 中没有文档,则从 IRequestService 中获取它,然后将其保存到 sessionStorage。 我尝试了这种方法,但出现类型错误</p><pre>Type 'Promise&lt;void | GetDocumentResult&gt;' is not assignable to type 'Promise&lt;GetDocumentResult&gt;'.</pre><p> 代码如下所示:</p><pre> getDocument(requestId: string, documentId: DocumentID, requestService: IRequestService): Promise&lt;GetDocumentResult&gt; { if (this.storageKey in sessionStorage) { const documentsMap: Map&lt;DocumentID, GetDocumentResult&gt; = new Map(JSON.parse(sessionStorage.getItem(this.storageKey).)) if (documentsMap.get(documentId).== undefined) { return new Promise(resolve =&gt; resolve(documentsMap,get(documentId).)) } } return requestService.getDocument(requestId, documentId) .then(value =&gt; {this.setDocument(documentId, value)}) }</pre><p> 我期待 Promise&lt;GetDocumentResult&gt;.then 的返回类型是 Promise&lt;GetDocumentResult&gt;,但由于某种我不明白的原因,它是 Promise&lt;void | 获取文档结果&gt;</p><p> 有人知道为什么会这样吗?</p><p> 谢谢</p></div></object></void> - TypeScript Type 'Promise<void | Object>' is not assignable to type 'Promise<Object>' on Promise.then() 在 Promise.then() 中访问拖放 object? - Access drag-n-drop object inside Promise.then()? 如何在 promise.then 内部中断? - How to break while inside promise.then? 运行在 Promise.then() 中定义的函数 - Run a function defined inside a Promise.then() 打字稿抱怨诺言。然后 - Typescript complains on promise.then Promise.then 不是仅在服务器上的函数错误 - Promise.then is not a function error only on server 从 function 返回 object 并将引用传递给道具会给出我的 TypeScript 错误。 如果 object 直接放在 prop 中就不会发生 - Returning an object from a function and passing the reference to a prop gives my TypeScript error. Doesn't happen if object is put straight in prop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM