【问题标题】:Object is possibly undefined even if I check if it exists with a conditional即使我用条件检查它是否存在,对象也可能未定义
【发布时间】:2020-06-06 23:04:45
【问题描述】:

我正在尝试为 Firebase 编写一个打字稿云功能。即使我检查 change.after 是否像提到的here 那样存在,我仍然会得到 Object 可能未定义的错误。

这是我的代码:

export const toDashboardInfo = functions.firestore.document('maps/{mapId}').onWrite((change, context) => {  
  let userId;
  if(change.after){
    const after=change.after.data();
    userId=after.ownerId;
  }

下面是 vscode 中的截图:

我做错了什么?谢谢!

【问题讨论】:

    标签: typescript firebase google-cloud-functions


    【解决方案1】:

    正如您所提到的,您正在检查change.after 是否存在。当它发生时,您调用一个名为data() 的方法,该方法可以返回FirebaseFirestore.DocumentDataundefined。这意味着变量after 可以是这些类型中的任何一种,因为data() 方法的结果可能会返回undefined

    您还应该在访问其属性之前检查typeof after !== 'undefined' 是否存在。

    export const toDashboardInfo = functions.firestore.document('maps/{mapId}').onWrite((change, context) => {  
      let userId;
      if (change.after) {
        // change after exists
        const after = change.after.data();
    
        // after can be undefined as data() could return undefined
        if (typeof after !== 'undefined') {
          userId = after.ownerId; // it's safe to access ownerId
        }
      }
    }
    

    另外,如果你使用 typescript v3.7 及更高版本,你可以使用Optional chaining。代码看起来类似于:

    export const toDashboardInfo = functions.firestore.document('maps/{mapId}').onWrite((change, context) => {  
      const after = change.after?.data();
      const userId = after?.ownerId || 'default value';
    }
    

    如果userId 在没有数据或ownerId 返回时可以是undefined,则可以跳过|| 'default value' 部分。

    【讨论】:

      猜你喜欢
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      • 2019-02-05
      • 2020-02-27
      • 1970-01-01
      • 2018-09-11
      • 1970-01-01
      相关资源
      最近更新 更多