← Back to TypeScript Course | Chapter 15: TypeScript with APIs | Lesson 1 of 6

Types के साथ Fetch API

Fetch API TypeScript applications को web servers से data request करने देता है। TypeScript request data और API responses describe कर सकता है ताकि आपका asynchronous code सुरक्षित और समझने में आसान हो।
Syntax
typescript
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

typescript
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

typescript
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

typescript
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

typescript
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

typescript
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));
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह मान लेना कि fetch HTTP 404 या 500 पर reject होगा, जब यह सिर्फ network errors पर reject होता है, इसलिए आपको response.ok जांचना चाहिए।
  2. Promise<User> लिखना और इस पर भरोसा करना, जब response.json() any return करता है और TypeScript असली data नहीं जांचता।
  3. response.json() से पहले await भूल जाना, इसलिए आपको object के बजाय एक Promise मिलता है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.