You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Firebase云函数中TypeScript报错‘Object is possibly undefined’

解决Firebase云函数中Stripe API的"Object is possibly undefined"错误

嘿,我来帮你搞定这个TypeScript类型错误!这个报错是因为TypeScript的严格类型检查机制在起作用——它认为customer.sources或者customer.sources.data有可能是undefined,直接访问会有风险。

下面给你几个实用的解决办法:

方法1:使用可选链操作符(最推荐)

可选链?.会自动处理属性为undefined的情况,如果customer.sources不存在,整个表达式会返回undefined,不会触发报错。修改后的代码如下:

const existingSource = customer.sources?.data.filter( (s) => s.id === source).pop();

方法2:非空断言(仅当你确定属性一定存在时使用)

如果你能100%保证customer.sources永远不会是undefined,可以用非空断言!来告诉TypeScript忽略这个类型检查:

const existingSource = customer.sources!.data.filter( (s) => s.id === source).pop();

⚠️ 注意:这个方法有风险,如果运行时customer.sources真的是undefined,会直接抛出错误,所以只在你完全确定的场景下用。

方法3:显式类型检查(最严谨)

先判断customer.sources和customer.sources.data是否存在,再执行过滤操作,这样既符合TypeScript的类型要求,也能避免运行时错误:

let existingSource;
if (customer.sources && customer.sources.data) {
  existingSource = customer.sources.data.filter( (s) => s.id === source).pop();
} else {
  // 这里可以处理sources不存在的情况,比如设置默认值或者抛出友好错误
  existingSource = undefined;
}

另外,关于你的getOrCreateCustomer函数,还可以优化一下类型安全性:因为stripe.customers.retrieve可能返回DeletedCustomer类型,你可以加个判断确保返回的是有效客户:

export const getOrCreateCustomer = async(uid: string) => {
  const user = await getUser(uid);
  const customerId = user?.stripeCustomerId; // 这里也可以用可选链优化

  if (!customerId) {
    return createCustomer(uid);
  } else {
    const customer = await stripe.customers.retrieve(customerId);
    // 确保不是已删除的客户
    if ('deleted' in customer && customer.deleted) {
      return createCustomer(uid);
    }
    return customer;
  }
}

内容的提问来源于stack exchange,提问作者Marcus Gallegos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:48:39