Real World Example

Typing a Payment Checkout Script

Payment gateways like Razorpay and PayPal load a <script> that defines a global constructor. There is no npm import, so Indian e-commerce front ends declare the global themselves. The runnable part below simulates the script by defining the global at runtime.

Example

declare global {
  interface CheckoutOptions {
    key: string;
    amount: number; // paise
    currency: "INR";
    name: string;
    order_id: string;
    handler: (response: { payment_id: string; order_id: string; signature: string }) => void;
  }
  var Checkout: new (options: CheckoutOptions) => { open(): void };
}

// Simulates the gateway's <script> tag defining the global
globalThis.Checkout = class {
  constructor(private o: CheckoutOptions) {}
  open() {
    console.log(`Opening checkout for ${this.o.name}: Rs. ${this.o.amount / 100}`);
    this.o.handler({ payment_id: "pay_29QQoUBi66xm2f", order_id: this.o.order_id, signature: "3f9a1c" });
  }
};

const checkout = new Checkout({
  key: "rzp_test_123",
  amount: 129900,
  currency: "INR",
  name: "ShopEase",
  order_id: "order_9A33XWu170gUtm",
  handler: (res) => console.log("Paid:", res.payment_id, "for", res.order_id),
});
checkout.open();

export {};

Output

Opening checkout for ShopEase: Rs. 1299
Paid: pay_29QQoUBi66xm2f for order_9A33XWu170gUtm