如何修复 firestore 的此 TSLint(对象可能是 'undefined')错误

How to fix this TSLint (Object is possibly 'undefined') error for firestore

我正在使用下面这个 link 中的 firesotre 示例。无论我收到错误 Object is possibly 'undefined' for the data in data.name。我很确定文件中有我的名字。请问如何解决这个问题。

// Listen for updates to any `user` document.
exports.countNameChanges = functions.firestore
    .document('users/{userId}')
    .onUpdate((change, context) => {
      // Retrieve the current and previous value
      const data = change.after.data();
      const previousData = change.before.data();

      // We'll only update if the name has changed.
      // This is crucial to prevent infinite loops.
      if (data.name == previousData.name) return null;

      // Retrieve the current count of name changes
      let count = data.name_change_count;
      if (!count) {
        count = 0;
      }

      // Then return a promise of a set operation to update the count
      return change.after.ref.set({
        name_change_count: count + 1
      }, {merge: true});
    });

如果您查看 change.after.data() 的 TypeScript 定义,您会看到数据方法被声明为 return 未定义或对象。由于它可能 return 未定义,因此当 TypeScript 处于严格模式时,您需要在开始访问其属性或方法之前检查这种情况。即使您完全确定您的文档将具有命名的 属性.

,您也必须这样做

您可以禁用严格模式(我不推荐这样做 - 严格模式会保护您免受编程错误),或者您可以在开始使用它们之前检查 datapreviousData

const data = change.after.data();
const previousData = change.before.data();
if (data && previousData) {
    // do stuff with them
}