TypeScript के साथ Axios
In this page:
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
// 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
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
// 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
// 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
// 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);
}
- Generic भूल जाना,
axios.get(url), इसलिएresponse.dataanyहो जाता है। responseको सीधे पढ़ना बजायresponse.dataके, क्योंकि parsed body.dataके अंदर है।- यह मान लेना कि generic type response validate करता है, जब यह सिर्फ TypeScript को बताता है कि क्या expect करना है।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: