Types के साथ Fetch API
In this page:
const response = await fetch("url");
const data: Type = await response.json();
Basic Typed Fetch
एक basic typed fetch call अब भी native fetch API से Promise<Response> return करती है — असली data typing .json() call करने के बाद ही होती है, क्योंकि fetch को खुद नहीं पता कि response body का shape क्या होगा।
उदाहरण: Basic Typed Fetch
interface User {
id: number;
name: string;
}
async function getUser(): Promise<User> {
const response = await fetch("data.php");
return response.json();
}
getUser().then(console.log);
HTTP Responses जांचना
Body parse करने से पहले response.ok जांचना ज़रूरी है क्योंकि एक typed fetch call HTTP error statuses जैसे 404 पर भी succeed (resolve) होती है — fetch सिर्फ network failures पर reject होता है, कभी HTTP error codes पर नहीं।
उदाहरण: Checking HTTP Responses
async function getUser() {
const response = await fetch("data.php");
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return response.json();
}
getUser().then(console.log).catch(console.error);
Types के साथ POST Requests
एक typed POST request JSON.stringify से एक typed payload object के साथ request body set करती है और आमतौर पर response को उसी तरह annotate करती है जैसे GET में, क्योंकि fetch खुद अपनी typing में request types में फर्क नहीं करता।
उदाहरण: POST Requests with Types
interface NewUser {
name: string;
}
async function createUser(payload: NewUser) {
const response = await fetch("data.php", {
method: "POST",
body: JSON.stringify(payload),
});
return response.json();
}
createUser({ name: "Ravi" }).then(console.log);
Fetch से Typed Arrays
Fetch से arrays type करने का मतलब है यह assert या validate करना कि parsed JSON असल में expected item type का एक array है, क्योंकि .json() का return type any है और यह mismatched shape खुद नहीं पकड़ेगा।
उदाहरण: Typed Arrays from Fetch
interface Item {
id: number;
}
async function getItems(): Promise<Item[]> {
const response = await fetch("data.php");
const data = await response.json();
if (!Array.isArray(data)) throw new Error("Expected an array");
return data;
}
getItems().then(console.log);
Reusable Fetch Helper
एक reusable fetch helper fetch-then-.json()-then-validate pattern को एक generic function में wrap करता है, ताकि callers को हर call site पर response-checking boilerplate दोबारा लिखे बिना एक typed result मिले।
उदाहरण: Reusable Fetch Helper
async function fetchJson<T>(url: string): Promise<T> {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}
interface User { name: string; }
fetchJson<User>("data.php").then((user) => console.log(user.name));
- यह मान लेना कि
fetchHTTP 404 या 500 पर reject होगा, जब यह सिर्फ network errors पर reject होता है, इसलिए आपकोresponse.okजांचना चाहिए। Promise<User>लिखना और इस पर भरोसा करना, जबresponse.json()anyreturn करता है और TypeScript असली data नहीं जांचता।response.json()से पहलेawaitभूल जाना, इसलिए आपको object के बजाय एक Promise मिलता है।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: