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 progress
65%

Step 1 of 5

Type API responses

Define Post interface matching JSONPlaceholder. getPost(id: number): Promise<Post>. Trust but verify at boundaries.

Type API responsesDrag stickies · tap for tips
Study mapDrag stickies · tap for tipsKeep it shortdrag · tap →Name the waitdrag · tap →Scope locatorsdrag · tap →Trace when stuckdrag · tap →One browser firstdrag · tap →Isolate statedrag · tap →Assert the UIdrag · tap →Retry wiselydrag · tap →Seed datadrag · tap →Close the loopdrag · tap →Keep it shortdrag · tap →Name the waitdrag · tap →Scope locatorsdrag · tap →Trace when stuckdrag · tap →One browser firstdrag · tap →Isolate statedrag · tap →Pathwise hackdrag · tap →Type API responsesdrag · tap →Try thisdrag · tap →Follow the dashed drag · tap →

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.