对象可能是‘未定义’

对象可能是‘未定义’

本文介绍了如何修复 Typescript 错误“对象可能是‘未定义’"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个将使用 Stripe API 来处理付款的云函数.这是在一个firebase项目中.当我运行 firebase deploy 时,我收到错误对象可能'未定义'" const existingSource = customer.sources.data.filter( (s) => s.id ===source).pop();我不确定如何解决这个问题.

I'm building a cloud function that will use the Stripe API to process payments. This is within a firebase project. When I run firebase deploy I get the error "Object is possible 'undefined'" const existingSource = customer.sources.data.filter( (s) => s.id === source).pop();I'm not sure how to resolve this.

这是我存在 getorCreateCustomer 的 xxx.ts

Here is my xxx.ts where getorCreateCustomer exists

/** Read the stripe customer ID from firestore, or create a new one if missing */
export const getOrCreateCustomer = async(uid: string) => {
    const user = await getUser(uid);
    const customerId = user && user.stripeCustomerId;

    //if missing customerId, create it
    if (!customerId) {
        return createCustomer(uid);
    }
    else {
        return stripe.customers.retrieve(customerId);
    }
}

推荐答案

7个月后,我找到了最好的解决方案.

7 months later, I figured out the best solution.

我只是将 firebase 可调用函数的内容包装在下面的 if/else 语句中.这有点多余,但它有效.

I simply wrapped the the contents of the firebase callable function in the following if/else statement. It's a bit redundant but it works.

if (!context.auth) {
    // Throwing an HttpsError so that the client gets the error details.
    throw new functions.https.HttpsError('failed-precondition', 'The function must be called ' +
        'while authenticated.');
  }
  else{ ...copy function code here }

如果您不关心身份验证部分,您可以简单地将上下文类型定义为 any.

If you don't care about the authentication piece you can simply define the type of context as any.

(data, context:any)

这篇关于如何修复 Typescript 错误“对象可能是‘未定义’"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 10:58