Manuals / TypeScript / Chapter 8
D · Integration · intermediate · Week 4 · Chapter 8 of 11
Typing APIs & external data
API responses are unknown until validated. Type fetch JSON with interfaces. Zod or manual guards for runtime check. unknown vs any — always prefer unknown for external data. Typed environment variables and module augmentation preview.
Path progress65%
Step 1 of 5
Type API responses
Define Post interface matching JSONPlaceholder. getPost(id: number): Promise<Post>. Trust but verify at boundaries.
Example
interface Post {
id: number
userId: number
title: string
body: string
}
async function getPost(id: number): Promise<Post> {
const res = await fetch(`${BASE}/posts/${id}`)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return res.json() as Promise<Post> // trust + validate in prod
}Do this now
Type all fetch functions with explicit return types. No bare Promise<any>.
Was this step clear?
Chapter learning outcomes
- Typing fetch responses
- unknown vs any
- Type guards
- Zod lite
- Env typing
Clear these before you leave
Side quest
API client module
Typed api/client.ts: getPosts(): Promise<Post[]>, createPost(input: CreatePostInput): Promise<Post>. Validated responses.