Fetch response typing
TypeScript'da fetch javobini type'lash: res.json() any bo'lishi, type berish, res.ok tekshiruvi, qayta ishlatiladigan fetchJson<T> helper, POST so'rov va generic type va'da ekani.
85-dars
Fetch response typing
fetch qaytargan javob .json() qilinganda type'i any bo'ladi. Ya'ni TS serverdan nima kelishini bilmaydi. Type'ni o'zingiz berasiz, lekin bu faqat va'da, haqiqiy tekshiruv emas.
Muammo
const res = await fetch("/api/user/1");
const user = await res.json(); // tip: any
user.nmae; // ❌ xato yozildi, lekin TS indamaydi
any bo'lgani uchun har qanday xato o'tib ketadi.
1-qadam: type berish
type User = {
id: number;
name: string;
email: string;
};
const res = await fetch("/api/user/1");
const user: User = await res.json();
user.nmae;
// ❌ Property 'nmae' does not exist on type 'User'. Did you mean 'name'?
user.name; // string
2-qadam: res.ok'ni tekshirish
fetch 404 yoki 500'da xato tashlamaydi. Tekshirmasangiz, xato javobini User deb o'ylab ketasiz:
const res = await fetch("/api/user/1");
if (!res.ok) {
throw new Error(`Xato: ${res.status}`);
}
const user: User = await res.json();
3-qadam: qayta ishlatiladigan generic funksiya
async function fetchJson<T>(url: string, init?: RequestInit): Promise<T> {
const res = await fetch(url, init);
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${res.statusText}`);
}
return res.json() as Promise<T>;
}
Ishlatish:
const user = await fetchJson<User>("/api/user/1");
user.email; // ✅ string
const posts = await fetchJson<Post[]>("/api/posts");
posts.map((p) => p.title); // ✅
Real misol: POST so'rov
type CreateOrder = { productId: number; quantity: number };
type Order = { id: number; status: "pending" | "paid"; total: number };
const order = await fetchJson<Order>("/api/orders", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ productId: 5, quantity: 2 } satisfies CreateOrder),
});
if (order.status === "paid") {
console.log("To'landi:", order.total);
}
satisfies (38-dars) yuborilayotgan ma'lumot ham to'g'ri shaklda ekanini tekshiradi, lekin uni Order'ga kengaytirib yubormaydi.
⚠️ Muhim ogohlantirish
const user = await fetchJson<User>("/api/user/1");
Bu TS'ga "menga ishon, bu User" degani — T faqat qaytish type'ida turgani uchun, u yashirin as (51-dars). Agar server { id: "1", fullName: "Ali" } qaytarsa, TS buni bilmaydi, xato runtime'da chiqadi. Haqiqiy tekshiruv uchun runtime validatsiya kerak: type guard (46-dars) yoki Zod kabi schema kutubxonasi.
Eslab qolish uchun
res.json()→any, darhol type bering.res.ok'ni doim tekshiring,fetch404'da xato tashlamaydi.fetchJson<T>kabi bitta helper yozing.- Generic type = va'da, validatsiya emas.