【问题标题】:How to fix this TSLint (Object is possibly 'undefined') error for firestore如何修复 Firestore 的此 TSLint(对象可能是“未定义”)错误
【发布时间】:2019-05-18 08:23:49
【问题描述】:

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

// 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});
    });

【问题讨论】:

    标签: typescript google-cloud-firestore tslint


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2019-08-20
      • 2019-12-09
      • 1970-01-01
      • 2019-08-04
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 2019-08-31
      相关资源
      最近更新 更多