即使我使用条件检查对象是否存在,对象也可能未定义

jwt*_*ees 1 firebase typescript google-cloud-functions

我正在尝试为 Firebase 编写一个打字稿云函数。即使我像这里提到的那样检查 change.after 是否存在,我仍然会收到 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;
  }
Run Code Online (Sandbox Code Playgroud)

这是vscode中的截图: 在此处输入图片说明

我究竟做错了什么?谢谢!

Daw*_*ski 5

正如你提到的,你正在检查是否change.after存在。当它发生时,您调用它的一个方法,该方法data()可以返回FirebaseFirestore.DocumentDataor undefined。这意味着变量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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

此外,如果您使用的是 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';
}
Run Code Online (Sandbox Code Playgroud)

你可以跳过|| 'default value'部分,如果userId可以undefined没有数据,或者当ownerId被返回。