stripe-betalningar - Vad är det bästa sättet att kontrollera vilket objekt som returneras från ett API i TypeScript?
Stripe kan returnera 3 olika objekttyper som kunden. Jag vill ha kund-ID:t vilket är vad som normalt returneras.
Det jag har nedan är ganska fult.
Finns det ett bättre sätt att göra detta?
const stripeCustomer: string | Stripe.Customer | Stripe.DeletedCustomer = checkoutSession.customer;
let stripeCustomerId: string;
if (stripeCustomer instanceof Object && "email" in stripeCustomer) {
// customer is of type Stripe.Customer
stripeCustomerId = stripeCustomer.id;
} else if (typeof stripeCustomer === 'string') {
// customer is id
stripeCustomerId = stripeCustomer;
} else {
// customer is of type Stripe.DeletedCustomer
stripeCustomerId = null;
}
Svar #1
Du kan använda användardefinierade typvakter, som låter dig ansluta din egen anpassade typkontrollogik till typsystemet.
När de är sanna för ett objekt, informerar de flödeskänslig typning om att objektet har den angivna typen:
function isStripeCustomer(object: any): object is Stripe.Customer {
return object instanceof Object
&& "object" in object
&& object.object === 'customer'
&& !object.deleted
}
function isStripCustomerID(object: any): object is string {
return typeof object === "string"
}
function isStripeDeletedCustomer(object: any): object is Stripe.DeletedCustomer {
return object instanceof Object
&& "object" in object
&& object.object === 'customer'
&& object.deleted
}
const customer: string | Stripe.Customer | Stripe.DeletedCustomer = checkoutSession.customer;
let stripeCustomerId: string | null
if (isStripeCustomer(customer)) {
stripeCustomerId = customer.id
} else if (isStripCustomerID(customer)) {
stripeCustomerId = customer;
} else if (isStripeDeletedCustomer(customer) {
stripeCustomerId = null;
} else {
// It was none of the known types. Perhaps a new type of result was
// add in a future version of their API?
}
Svar #2
Det grundläggande konceptet du använder är det rätta. Du kan förbättra det med typvakter för att göra det typ-säkert och möjliggöra att identifiera problem vid kompileringstid:
interface Customer {
id: string;
}
type CustomerResponse = Customer | string | null;
function isCustomerObject(customer: CustomerResponse): customer is Customer {
return customer != null && typeof customer === "object" && customer.id != null;
}
function isString(str: CustomerResponse): str is string {
return typeof str === "string";
}
function identify(obj: Customer | string | null) {
if (isCustomerObject(obj)) {
console.log(obj, "is a customer with ID", obj.id);
} else if (isString(obj)) {
console.log(obj, "is a string with value", obj);
} else {
console.log(obj, "is null");
}
}
const customerObject: Customer = {
id: "123"
};
identify(customerObject);
identify("123");
identify(null);
Se samma kod på TypeScript-lekplatsen.
