Careeroza
Real World Example
Reading a Webhook Payload Safely
Payment gateways like Razorpay send webhooks (HTTP calls to your server) when a payment succeeds. The body is untrusted JSON, so it should be unknown until checked.
Example
type PaymentEvent = { event: string; amount: number };
function isPaymentEvent(value: unknown): value is PaymentEvent {
return typeof value === "object" && value !== null &&
"event" in value && typeof value.event === "string" &&
"amount" in value && typeof value.amount === "number";
}
function handleWebhook(body: string): void {
const data: unknown = JSON.parse(body);
if (!isPaymentEvent(data)) {
console.log("Rejected: invalid payload");
return;
}
console.log(`Event ${data.event}: Rs. ${(data.amount / 100).toFixed(2)}`);
}
handleWebhook('{"event": "payment.captured", "amount": 49900}');
handleWebhook('{"event": "payment.captured", "amount": "49900"}');Output
Event payment.captured: Rs. 499.00 Rejected: invalid payload
Note: value is PaymentEvent is a type guard. You will learn it fully in the medium level (Narrowing).