Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
“如何修复Typescript错误”;对象可能是';未定义'&引用;_Typescript_Firebase_Google Cloud Functions_Stripe Payments - Fatal编程技术网

“如何修复Typescript错误”;对象可能是';未定义'&引用;

“如何修复Typescript错误”;对象可能是';未定义'&引用;,typescript,firebase,google-cloud-functions,stripe-payments,Typescript,Firebase,Google Cloud Functions,Stripe Payments,我正在构建一个云函数,它将使用StripeAPI来处理支付。这在firebase项目中。当我运行firebase deploy时,我得到错误“对象可能是“未定义的”const existingSource=customer.sources.data.filter((s)=>s.id==source.pop() 我不知道如何解决这个问题 这是我的xxx.ts,getorCreateCustomer就在这里 /** Read the stripe customer ID from firestore

我正在构建一个云函数,它将使用StripeAPI来处理支付。这在firebase项目中。当我运行
firebase deploy
时,我得到错误“对象可能是“未定义的”
const existingSource=customer.sources.data.filter((s)=>s.id==source.pop()
我不知道如何解决这个问题

这是我的xxx.ts,getorCreateCustomer就在这里

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

根据函数的定义和内容,TypeScript无法推断getOrCreateCustomer的返回类型。它假设它可以返回undefined,而它的严格模式要求您引用未定义对象上的属性,这将导致运行时出错

您需要做的是将返回类型声明为不可能未定义的类型,并确保函数体中的代码在该保证上是正确的(否则将出现新错误)

如果您不能做到这一点(但您确实应该做到),那么您可能希望在tsconfig.json文件中禁用严格模式,因为这就是在代码中强制执行此级别正确性的原因


我建议第一种选择,即使您必须编写更多的代码行,因为它更好地使用TypeScript的键入系统。

正如@Doug所提到的,但您也可以编写逻辑,以确保
customer.sources.data
的每一部分都不是未定义的

即:


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

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

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 }
如果您不关心身份验证部分,您可以简单地将上下文的类型定义为任意类型


请编辑问题以显示
getOrCreateCustomer
,因为这是返回可能未定义对象的内容。@DougStevenson很抱歉,我编辑并添加了该文件。希望你能帮忙。
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 }
(data, context:any)