【问题标题】:How to fix Typescript error "Object is possibly 'undefined'"如何修复 Typescript 错误“对象可能是‘未定义’”
【发布时间】:2019-08-20 22:09:31
【问题描述】:

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

这是我存在 getorCreateCustomer 的 xxx.ts

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

【问题讨论】:

  • 请编辑问题以显示getOrCreateCustomer,因为这会返回可能未定义的对象。
  • @DougStevenson 抱歉,我编辑并添加了文件。希望你能帮忙。

标签: typescript firebase google-cloud-functions stripe-payments


【解决方案1】:

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

您需要做的是将返回类型声明为不可能未定义的内容,并确保函数主体中的代码在该保证上是正确的(否则您会得到一个新错误) .

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

我建议第一个选项,即使您必须编写更多代码行,因为它可以更好地使用 TypeScript 的打字系统。

【讨论】:

    【解决方案2】:

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

    即:

    const { sources } = customer
    
    if (sources) {
      const { data } = sources 
      if (data) {
         // then filter / etc etc ...
      }
    }
    

    【讨论】:

      【解决方案3】:

      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 }
      

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

      (data, context:any)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-29
        • 1970-01-01
        • 1970-01-01
        • 2019-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多