#typescript
#project
#api
Day 29: Project - Type-Safe API Client
The Capstone
Welcome to Day 29! Letβs build something real using Generics, Interfaces, and Async/Await.
The Goal
Create a function request that:
- Wraps
fetch. - Is Generic (returns typed data).
- Handles errors.
Step 1: Define Interfaces
interface APIResponse<T> {
data: T;
status: number;
}
interface User {
id: number;
name: string;
}
Step 2: The Generic Function
async function request<T>(url: string): Promise<APIResponse<T>> {
const response = await fetch(url);
const json = await response.json();
if (!response.ok) {
throw new Error(\`Error \${response.status}\`);
}
return {
data: json as T,
status: response.status
};
}
Step 3: Usage
async function main() {
try {
const response = await request<User>("https://api.example.com/user/1");
// TypeScript knows response.data is User!
console.log(response.data.name);
} catch (error) {
console.error(error);
}
}
Challenge for Today
- Implement a
postmethod in your client. - It should take a second generic
BodyType. function post<ReturnType, BodyType>(url: string, body: BodyType)
See you on Day 30 for the Finale!