Course contentsShow
← TypeScript
Lesson 1272 of 1,79630. Type-Safe APIsFree lesson

Casting fetch Results with Type Assertions

Using 'as' to assert the shape of JSON responses, understanding this is a promise, not a guarantee.

Casting fetch Results with Type Assertions

What you'll learn: How to use as to give shape to JSON responses from fetch, while understanding this is a developer promise, not a runtime guarantee.


When you call fetch() and parse the response with .json(), TypeScript sees the result as any (or unknown depending on your settings). The runtime data could be anything—TypeScript has no way to verify what the server actually sent.

Type assertions let you tell TypeScript: "Trust me, I know this data has this shape."

type User = {
  id: number;
  name: string;
  email: string;
};

async function getUser(id: number): Promise<User> {
  const response = await fetch(`/api/users/${id}`);
  const data = await response.json(); // data is 'any'
  
  return data as User; // We assert this is a User
}

This Is a Promise, Not a Guarantee

Here's the critical truth: type assertions don't validate anything at runtime. They're purely compile-time instructions that disappear when your code runs.

Think of it like signing a contract without reading it. You're promising the compiler "this data matches User", but if the API returns { status: "error" } instead, your code will happily treat it as a User and likely crash later.

// If the API returns { error: "Not found" }
const user = data as User;
user.name.toUpperCase(); // Runtime error! 'name' is undefined

The assertion gave you autocomplete and type safety in your editor, but it didn't protect you from bad data.

When This Pattern Works

Use type assertions for fetch results when:

  • You control the API and know its shape
  • The API contract is stable
  • Runtime validation happens elsewhere
  • You're prototyping and will add validation later

This is a pragmatic starting point, not the final solution. Later, you'll learn runtime validation libraries that actually check the data matches your types.

Key Takeaway: Type assertions with as tell TypeScript what shape to expect from JSON, but they're a compile-time convenience only—the runtime data could still be anything, and TypeScript won't catch mismatches.