TypeScript中如何优雅判断Stripe API返回的客户对象类型并获取ID?
优化Stripe客户ID获取的实现方式
你的现有代码可以通过利用Stripe类型的内置特征来简化,同时让类型判断更准确:
方式一:简化三元表达式实现
直接根据类型特征做判断,代码更紧凑:
const stripeCustomer: string | Stripe.Customer | Stripe.DeletedCustomer = checkoutSession.customer; // 修正类型为 string | null,因为存在返回null的情况 const stripeCustomerId: string | null = typeof stripeCustomer === 'string' ? stripeCustomer : stripeCustomer.deleted ? null : stripeCustomer.id;
方式二:自定义类型守卫(类型更安全)
如果需要更明确的类型区分,可编写类型守卫函数,让TS能精准推断类型:
// 类型守卫:判断是否为有效Stripe客户 function isStripeCustomer(customer: unknown): customer is Stripe.Customer { return typeof customer === 'object' && customer !== null && !('deleted' in customer) && 'id' in customer; } // 类型守卫:判断是否为已删除的Stripe客户 function isDeletedStripeCustomer(customer: unknown): customer is Stripe.DeletedCustomer { return typeof customer === 'object' && customer !== null && (customer as Stripe.DeletedCustomer).deleted === true && 'id' in customer; } // 使用示例 const stripeCustomer: string | Stripe.Customer | Stripe.DeletedCustomer = checkoutSession.customer; let stripeCustomerId: string | null; if (typeof stripeCustomer === 'string') { stripeCustomerId = stripeCustomer; } else if (isStripeCustomer(stripeCustomer)) { stripeCustomerId = stripeCustomer.id; } else { stripeCustomerId = null; }
优化说明
- 原代码用
email字段判断有效客户不够严谨,因为Stripe Customer对象可能没有email(比如创建时未提供),而Stripe的DeletedCustomer类型自带deleted: true属性,用这个判断已删除客户更可靠。 - 修正了
stripeCustomerId的类型声明,原代码中赋值null但声明为string会导致TS类型错误,改为string | null更符合实际逻辑。
内容的提问来源于stack exchange,提问作者MadMac
相关产品推荐
相关产品推荐

