Ad

How To Fix Typescript Error "Object Is Possibly 'undefined'"

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.

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

enter image description here

Ad

Answer

7 months later, I figured out the best solution.

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 }

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

(data, context:any)
Ad
source: stackoverflow.com
Ad