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

Type Guards for Response Validation

Writing runtime type guards to verify the response matches your type assertion before using it.

Type Guards for Response Validation

You'll learn: How to safely verify that runtime API data actually matches your type assertions before using it in type-safe code.

The Problem

You just created a beautiful type interface for your API response and used a type assertion:

interface User {
  id: number;
  name: string;
  email: string;
}

const response = await fetch('/api/user/123');
const user = await response.json() as User;

But here's the uncomfortable truth: that as User is a lie. TypeScript trusts you completely, but the actual runtime data might be anything—malformed JSON, missing fields, wrong types, or server errors. Your type assertion doesn't validate anything; it just tells TypeScript to pretend.

Type Guards to the Rescue

A type guard is a runtime function that actually checks if the data matches your expected shape. It returns a boolean, but TypeScript understands its meaning through a type predicate.

function isUser(obj: unknown): obj is User {
  return (
    typeof obj === 'object' &&
    obj !== null &&
    'id' in obj &&
    typeof (obj as any).id === 'number' &&
    'name' in obj &&
    typeof (obj as any).name === 'string' &&
    'email' in obj &&
    typeof (obj as any).email === 'string'
  );
}

Notice the return type: obj is User. That's a type predicate—it tells TypeScript that if this function returns true, the parameter is definitely a User.

Using the Type Guard

Now you can validate before trusting:

const response = await fetch('/api/user/123');
const data: unknown = await response.json();

if (isUser(data)) {
  // TypeScript now KNOWS data is User
  console.log(data.name.toUpperCase());
} else {
  throw new Error('Invalid user data received');
}

Inside that if block, TypeScript narrows data from unknown to User. You get type safety and runtime validation.

Why This Matters

Think of type guards as border checkpoints between the unsafe outside world (network responses) and your type-safe application code. Without them, your types are wishful thinking. With them, you enforce the contract at runtime.

Key Takeaway: Type guards transform type assertions from dangerous lies into verified facts by actually checking runtime data structure before TypeScript narrows the type.