Course contentsShow
← TypeScript
Lesson 925 of 1,79621. The unknown TypeFree lesson

Typing fetch with unknown Response Bodies

Explicitly type fetch results as unknown to avoid implicit any in response parsing.

Typing fetch with unknown Response Bodies

What you'll learn: How to explicitly type network responses as unknown to maintain type safety when fetching data from external APIs.

The Core Idea

When you use fetch() to retrieve data from an API, TypeScript doesn't magically know what shape that data will have. The response could be anything — valid JSON, malformed data, or something unexpected. By default, operations like response.json() return Promise<any>, which silently opts you out of type safety.

The solution: explicitly type your parsed response as unknown, then use type guards to safely narrow it to the shape you expect.

The Pattern in Action

async function fetchUser(id: number) {
  const response = await fetch(`/api/users/${id}`);
  
  // Explicitly type as unknown
  const data: unknown = await response.json();
  
  // Now you must narrow before use
  if (
    typeof data === "object" &&
    data !== null &&
    "name" in data &&
    typeof data.name === "string"
  ) {
    return data.name; // Safe to use
  }
  
  throw new Error("Invalid user data");
}

Without the : unknown annotation, data would implicitly be any, letting you access data.name without any checking — a recipe for runtime crashes.

Why This Matters

Network responses are inherently untrusted. Even if you control the API, deployments can desynchronize, schemas can change, or proxies can inject errors. Typing responses as unknown forces you to validate before using the data, catching shape mismatches at runtime instead of discovering them in production.

Key Takeaway: Always type fetch response bodies as unknown and narrow with type guards — never trust network data without validation.