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

TypeScript के साथ Axios

Axios एक HTTP client है जो convenient request और response handling देता है। TypeScript के साथ, Axios generic types API calls से return होने वाले data और servers को भेजे जाने वाले data को describe कर सकते हैं।
Syntax
typescript
const response = await axios.get<Type>("url");
const data: Type = response.data;

Typed GET Requests

Axios के साथ एक typed GET request axios.get<User>(url) जैसा एक generic type argument pass करती है, जो resolved response.data को सीधे type करता है, native fetch के विपरीत जहां आपको .json() अलग से call और type करना पड़ता है।

उदाहरण: Typed GET Requests

typescript
// import axios from "axios";
interface User { id: number; name: string; }
// const response = await axios.get<User>("/api/user");
// console.log(response.data.name);
console.log("axios.get<User>(url) types response.data directly");

Typed POST Requests

एक typed POST request वही generic pattern follow करती है, आप भेजने वाले request body और, generic argument के through, response में वापस expect की जाने वाली data के shape दोनों को type करते हुए।

उदाहरण: Typed POST Requests

typescript
interface NewUser { name: string; }
interface User { id: number; name: string; }
// const response = await axios.post<User>("/api/users", { name: "Ravi" } as NewUser);
console.log("POST body and response.data both typed via generics");

Axios Response Types

Axios का अपना AxiosResponse<T> type आपके data type को .status और .headers जैसे extra fields के साथ wrap करता है, तो raw fetch के विपरीत, पूरा response object — सिर्फ body नहीं — out of the box पूरी तरह typed होता है।

उदाहरण: Axios Response Types

typescript
// import { AxiosResponse } from "axios";
interface User { name: string; }
// const response: AxiosResponse<User> = await axios.get("/api/user");
// console.log(response.status, response.data.name);
console.log("AxiosResponse<T> wraps data with status and headers");

Axios Instances

axios.create() से बनाई एक Axios instance आपको एक typed base URL और default headers एक बार configure करने देती है, फिर उस pre-configured instance को config repeat करने के बजाय अपने app में हर request में reuse करने देती है।

उदाहरण: Axios Instances

typescript
// import axios from "axios";
// const api = axios.create({ baseURL: "https://api.example.com", headers: { "X-Key": "abc" } });
// const response = await api.get("/users");
console.log("axios.create() configures a reusable typed instance");

Axios Errors को Type करना

Axios errors को type करने का मतलब है एक caught unknown value को Axios के अपने isAxiosError type guard से narrow करना, जो फिर एक typed .response property expose करता है जो server के असली error status और body ले जाती है।

उदाहरण: Typing Axios Errors

typescript
// import axios from "axios";
try {
  throw new Error("Request failed");
} catch (err: unknown) {
  // if (axios.isAxiosError(err)) console.log(err.response?.status);
  if (err instanceof Error) console.log(err.message);
}
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. Generic भूल जाना, axios.get(url), इसलिए response.data any हो जाता है।
  2. response को सीधे पढ़ना बजाय response.data के, क्योंकि parsed body .data के अंदर है।
  3. यह मान लेना कि generic type response validate करता है, जब यह सिर्फ TypeScript को बताता है कि क्या expect करना है।
🔒

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.