Careeroza
Real World Example
A Typed API Client
Front ends at Flipkart, Razorpay or any SaaS company wrap HTTP calls in a small typed client. One generic method serves every endpoint, and each call site gets the exact response type. (Network is simulated here.)
Example
type Product = { id: number; name: string; price: number };
type Order = { id: string; total: number; status: "PLACED" | "SHIPPED" };
interface Endpoints {
"/products": Product[];
"/orders/latest": Order;
}
const fakeServer: { [K in keyof Endpoints]: Endpoints[K] } = {
"/products": [{ id: 1, name: "Kettle", price: 1299 }, { id: 2, name: "Toaster", price: 1899 }],
"/orders/latest": { id: "OD-77", total: 3198, status: "SHIPPED" },
};
class ApiClient {
private calls = 0;
async get<P extends keyof Endpoints>(path: P): Promise<Endpoints[P]> {
this.calls++;
return structuredClone(fakeServer[path]);
}
get callCount(): number { return this.calls; }
}
async function main() {
const api = new ApiClient();
const products = await api.get("/products"); // Product[]
const order = await api.get("/orders/latest"); // Order
console.log(products.map((p) => p.name).join(", "));
console.log(order.id, order.status, order.total);
console.log("calls:", api.callCount);
}
main();Output
Kettle, Toaster OD-77 SHIPPED 3198 calls: 2
Note: Mistyping the path (api.get("/product")) is a compile error, and the editor autocompletes the available endpoints.