【问题标题】:Firebase cloud functions - typescript - undefine typeFirebase 云函数 - 打字稿 - 未定义类型
【发布时间】:2019-06-01 14:26:06
【问题描述】:

我有一个有趣的问题...

我将official documentation 用于firestore-events

然后我从那里得到这个代码,以便测试和玩耍。

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

我放了那些进口的(所以也许我错过了一个)

import * as functions from 'firebase-functions';

import * as Storage from '@google-cloud/storage';
const gcs = new Storage.Storage();

我认为一切看起来都很好,但我收到以下错误消息:

src/index.ts:33:13 - error TS2532: Object is possibly 'undefined'.

33         if (data.name == previousData.name) return null;
               ~~~~

src/index.ts:33:26 - error TS2532: Object is possibly 'undefined'.

33         if (data.name == previousData.name) return null;
                            ~~~~~~~~~~~~

src/index.ts:36:21 - error TS2532: Object is possibly 'undefined'.

36         let count = data.name_change_count;
                       ~~~~

发生了什么事?我在这里缺少什么?有谁知道我做错了什么并且可以帮助我?我在想,文档中的一切都应该很好并且可行。

【问题讨论】:

    标签: typescript firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    事实上,它是工作代码,唯一抱怨的是你的 linter。

    实际上,问题是onUpdate在文档被创建、更新或删除时触发,所以如果文档被删除,change.after.data()可能是未定义的,这就是linter抱怨的原因。

    如果您的意图开始,我建议您在任何抱怨的行上使用// @ts-ignore,然后当您感觉更舒服时,您可以进行更多调查,这种情况是要进行一些验证以确保您正在执行该行,例如:

    if (previousData && data.name == previousData.name) return null;
    

    【讨论】:

      猜你喜欢
      • 2023-03-08
      • 2020-05-09
      • 1970-01-01
      • 1970-01-01
      • 2021-08-15
      • 2021-06-03
      • 2021-12-15
      • 1970-01-01
      • 2018-03-28
      相关资源
      最近更新 更多