API Responses की Typing
In this page:
interface ApiResponse {
property: type;
}
const data = (await response.json()) as ApiResponse;
Simple Response Interfaces
एक simple response interface एक API endpoint से return होने वाले हर field को उसके type के साथ list करता है, parse होने के बाद उस response को उपयोग करने वाली हर जगह आपको compile-time checking देते हुए।
उदाहरण: Simple Response Interfaces
interface UserResponse {
id: number;
name: string;
email: string;
}
const user: UserResponse = { id: 1, name: "Ravi", email: "[email protected]" };
console.log(user);
Nested API Responses
Nested API responses को छोटे interfaces compose करके type किया जाता है — जैसे एक User interface किसी Order interface के customer field के अंदर उपयोग होना — बजाय सब कुछ एक बड़े, reuse करने में मुश्किल type में flatten करने के।
उदाहरण: Nested API Responses
interface User {
name: string;
}
interface Order {
id: number;
customer: User;
}
const order: Order = { id: 1, customer: { name: "Ravi" } };
console.log(order.customer.name);
Optional और Nullable Fields
एक response interface में एक field को optional (?) या nullable (| null) मार्क करना यह reflect करता है कि API असल में क्या omit या null भेज सकता है, और इस distinction को skip करना missing data पर runtime crashes का एक आम source है।
उदाहरण: Optional and Nullable Fields
interface Profile {
bio?: string;
avatarUrl: string | null;
}
const profile: Profile = { avatarUrl: null };
console.log(profile);
Generic API Response Wrappers
एक generic API response wrapper — जैसे ApiResponse<T> जो status metadata के साथ एक data: T field रखता है — आपको हर endpoint के लिए response shape की outer structure दोबारा define करने के बजाय एक envelope type हर जगह reuse करने देता है।
उदाहरण: Generic API Response Wrappers
interface ApiResponse<T> {
data: T;
status: number;
}
interface User { name: string; }
const response: ApiResponse<User> = { data: { name: "Ravi" }, status: 200 };
console.log(response.data.name);
Runtime API Data Validate करना
चूंकि TypeScript के types runtime पर गायब हो जाते हैं, यह validate करना कि API data असल में अपने declared interface से match करता है (एक schema library या manual checks के साथ) यह पकड़ने का इकलौता तरीका है कि backend कहीं एक unexpected shape तो नहीं भेज रहा।
उदाहरण: Validating Runtime API Data
interface User { name: string; }
function isUser(value: any): value is User {
return typeof value?.name === "string";
}
const raw: any = { name: "Ravi" };
if (isUser(raw)) console.log(raw.name);
- हर field को required मार्क करना जब API कुछ omit कर सकता है, इसलिए missing values पर code crash करता है।
- एक nullable field को सिर्फ
stringtype करना जब API कभी-कभीnullreturn करता है। - यह मानना कि interface runtime पर response जांचता है, जब server से एक गलत shape भी pass हो जाती है।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: