TypeScript
/Intermediate
Typing API Responses
Definition
Creating interfaces that mirror the exact JSON structure returned by backend APIs to ensure frontend safety during data fetching.
Explain Like I'm New
When you call `fetch()`, TypeScript has literally no idea what data comes back over the internet. It assumes it is `any`. If you don't explicitly type the response, you lose all the benefits of TypeScript the second your app connects to the real world.
Real World Example
Typing a paginated API response: `{ page: number, total: number, data: User[] }` and casting the `fetch` result to this type.
Common Use Cases
- •Axios integration
- •Fetch API
- •React Query data typing
Interactive Example
// 1. Define the Expected Shape interface UserData { id: number; name: string; email: string; } // 2. Typing standard Fetch API async function fetchUser(id: number): Promise<UserData> { const response = await fetch(`/api/users/${id}`); if (!response.ok) throw new Error("Network error"); // You MUST cast the untyped JSON result const data = (await response.json()) as UserData; return data; } // 3. Typing with Axios (Much cleaner!) // import axios from 'axios'; // async function fetchUserAxios(id: number) { // // Axios allows you to pass the Generic directly into the .get method // const response = await axios.get<UserData>(`/api/users/${id}`); // return response.data; // TS knows this is UserData // }
Interview Questions
basic
- What does `fetch().json()` return by default in TypeScript?
intermediate
- How do you apply a type to an Axios response?
advanced
- What is the danger of manually typing API responses?