node.js - stripe.customers.retrieve 导致问题,因为它现在正在返回

我正在升级到最新的 Stripe API 版本 (2020-03-02),但我不确定如何访问我的客户对象上的值,因为它现在只显示 Stripe.Customer 和 Stripe 之间的属性联合。已删除客户。

关于如何检查类型并转换为 Stripe.Customer 类型的任何提示?

我收到以下错误:

Property 'metadata' does not exist on type 'Customer | DeletedCustomer'. Property 'metadata' does not exist on type 'DeletedCustomer'.

 const customer: Stripe.Customer | Stripe.DeletedCustomer = await stripe.customers.retrieve(customerId);
 const uid = customer.metadata.firebaseUID;

注意 Customer 和 DeletedCustomer 是接口(interface):

namespace Stripe {
     interface DeletedCustomer {
          id: string;
          object: 'customer';
          deleted: true;
        }
    
     interface Customer {
          id: string;
          metadata: Metadata;
    ...
    }
}

最佳答案

为了区分类型,您可以:

  1. 检查所需对象中是否存在非共享属性,
  2. (或/和)比较一个/这个属性值

在您的情况下,Stripe.DeletedCustomer 没有 metadata 属性,因此您可以简单地验证此属性是否存在,如果是,则“客户”是type "Stripe.Customer"else 是类型 "Stripe.DeletedCustomer":

const customer: Stripe.Customer | Stripe.DeletedCustomer = await stripe.customers.retrieve(customerId);

if(customer instanceof Object && "metadata" in customer) {
 // $customer is of type "Stripe.Customer"
 const uid = customer.metadata.firebaseUID;
}
else {
 // $customer is of type "Stripe.DeletedCustomer
}

@查看:https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types

关于node.js - stripe.customers.retrieve 导致问题,因为它现在正在返回 Stripe.Customer | Stripe .DeletedCustomer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62630607/

相关文章:

google-chrome - 报告 api : Is there a way to debug w

php - 如何在 Ubuntu 16.04 中安装 php-curl

python - 如何在 Tkinter 窗口上使用 for 循环创建多个框架?

flutter - 如何解决 PlatformException (PlatformExceptio

microsoft-graph-api - 在新的限制下使用 Microsoft Graph API

r - 控制 geom_line() 图表中的日期(x 轴)间隔

asp.net - 如何为网络浏览器的用户获取 AD 属性

python - 如何从不同的文件调用方法而不在python中导入它

swift - 达到最大时间戳计数,不会记录更多事件 Xcode

node.js - 错误 : getaddrinfo ENOTFOUND with docker-c