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

标签 node.js typescript stripe-payments

我正在升级到最新的 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/

相关文章:

javascript - Node.js - 单线程,非阻塞?

javascript - CSS中的 Stripe 元素样式设置

stripe-payments - 我什么时候应该考虑在 Stripe 中订阅 "active"?

javascript - meteor 路由错误 : There is no route for the path:/

javascript - express-subdomain 处理任何子域

javascript - 如何从嵌套数组中删除空元素

laravel - Stripe : Expire/Cancel subscription after n payments

typescript - 是否可以从数组创建 typescript 类型?

javascript - 使用 typescript react 选择键的通用类型

javascript - 类型定义文件