Firebase 云函数对象可能“未定义" [英] Firebase Cloud Functions Object possibly 'undefined'

查看:23
本文介绍了Firebase 云函数对象可能“未定义"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 typescript 中有以下代码,我在行中收到此错误:change.after.data();, Object is posibbly 'undefined':

I have the following code in typescript and i get this error on the line: change.after.data();, Object is posibbly 'undefined':

import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'

admin.initializeApp()

export const onEditModeUpdate = 
functions.firestore.document("Settings/ShiftsEditMode").onUpdate(change=> {
    const after = change.after.data();
    const payload = {
        data: {
            temp: String(after.temp),
            conditions: after.conditions
        }
    }
    return admin.messaging().sendToTopic("Settings/ShiftsEditMode", payload)
})

我想要做的是每当firestore中的某些内容发生变化时向我的应用程序发送通知,我遵循了官方文档但我收到了错误,我认为这与node.js版本有关.请帮忙?

what I want to do is to send to my app a notification whenever something in firestore changes, I followed the official documentation but I get the error, I think this has to do with node.js version. Any help, please?

推荐答案

您的 change 参数属于 Change 类型.如果你在 VSCode 中点击它,你会在这里看到它的定义:

Your change parameter is of type Change. If you click through to it in VSCode, you'll see it's definition here:

export declare class Change<T> {
    before?: T;
    after?: T;
    constructor(before?: T, after?: T);
}

注意它的 beforeafter 属性都是可选的,在类型中用 ? 标记.这意味着这些值可能是未定义的.

Notice that its before and after properties are both optional, marked with a ? in the type. This means that it's possible that the values are undefined.

tsconfig.json 中的 TypeScript 配置很可能包含 "strict": true 行,它告诉 TypeScript 在您尝试访问属性时不会警告您如果不先明确检查它,那可能是未定义的.这就是您在此处看到的错误.

It's likely that your TypeScript config in tsconfig.json contains a line for "strict": true, which tells TypeScript not warn you whenever you try to access a property that could be undefined without explicitly checking it first. That's the error you're seeing here.

您有两个选择:

1) 从 tsconfig.json 中删除该行

1) Remove that line from your tsconfig.json

2) 或者检查是否先定义

2) Or check to see if it's defined first

if (change.after) {
    const after = change.after.data();
    const payload = {
        data: {
            temp: String(after.temp),
            conditions: after.conditions
        }
    }
    return admin.messaging().sendToTopic("Settings/ShiftsEditMode", payload)
}
else {
    return null;
}

这篇关于Firebase 云函数对象可能“未定义"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆