【问题标题】:How to resolve typescript error 'possibly undefined object'? - ts(2532)如何解决打字稿错误“可能未定义的对象”? - ts(2532)
【发布时间】:2020-02-21 20:18:22
【问题描述】:

我正在尝试创建一个辅助函数(firebase 云函数)以将支付源附加到 Stripe 客户帐户。

这是我的代码:

export const attachSource = async(uid: string, source: string) => {

    const customer = await getOrCreateCustomer(uid);

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

    if (existingSource) {
        return existingSource;
    } 
    else {
        await stripe.customers.createSource(customer.id, { source: source });
        // update default
        return await stripe.customers.update(customer.id, { default_source: source });
    }
}

我尝试了可选链接customer.sources?.data,但这会引发几个错误。

还尝试将其包装在 if 语句中,如下所示:

if (customer && customer.sources && customer.sources.data) {
    const existingSource = customer.sources.data.filter(s => s.id === source).pop()

    if (existingSource) {
        return existingSource;
    } else {
        await stripe.customers.createSource(subscriber.id, { source: source});
        // update default
        return await stripe.customers.update(subscriber.id, {default_source: source});
    }
}

这会导致以下错误:Not all code paths return a value.ts(7030)

无法使用 ! 解决问题,因为 Stripe 中可能不存在付款来源。

【问题讨论】:

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


    【解决方案1】:

    您的if 语句似乎缺少else,因此封闭函数始终返回一个值:

    if (customer && customer.sources && customer.sources.data) {
    }
    else {
        // what do you want to return here?
    }
    

    【讨论】:

    • 谢谢。好问题 - 不确定需要退回什么...?
    猜你喜欢
    • 2021-06-03
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    • 2021-08-07
    • 2019-07-30
    • 2019-09-15
    • 2021-12-15
    相关资源
    最近更新 更多