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

Generic parseResponse Helper Function

Create a reusable generic function that takes a validator and returns typed or throws.

Generic parseResponse Helper Function

You'll learn: How to build a single, reusable function that validates unknown API data and returns strongly-typed results—or throws when validation fails.

The Problem: Repeated Validation Logic

Right now, you're probably writing validation code for every API call:

const data = await fetch('/api/user').then(r => r.json()); // unknown
if (typeof data === 'object' && data !== null && 'name' in data) {
  // use data.name
}

Every endpoint repeats this pattern. We can do better.

The Solution: A Generic Helper

Create a function that:

  1. Takes unknown input (API response)
  2. Takes a validator function (type predicate)
  3. Returns strongly typed data if valid
  4. Throws an error if invalid
function parseResponse<T>(
  data: unknown,
  validator: (value: unknown) => value is T
): T {
  if (validator(data)) {
    return data; // TypeScript knows data is T here
  }
  throw new Error('Validation failed');
}

Using the Helper

// Define your validator once
function isUser(value: unknown): value is { name: string; age: number } {
  return (
    typeof value === 'object' &&
    value !== null &&
    'name' in value &&
    typeof value.name === 'string' &&
    'age' in value &&
    typeof value.age === 'number'
  );
}

// Use it everywhere
const apiData: unknown = await fetch('/user').then(r => r.json());
const user = parseResponse(apiData, isUser);
// user is { name: string; age: number } — fully typed!
console.log(user.name.toUpperCase());

Why This Works

  • Generic <T>: The function doesn't care what type you're validating—it adapts
  • Type predicate parameter: validator: (value: unknown) => value is T tells TypeScript "if this returns true, narrow to T"
  • Safe narrowing: Inside the if, TypeScript knows data is T, so the return is type-safe
  • Fail loudly: The throw ensures bad data never leaks through

Real-World Pattern

// Many validators, one helper
const user = parseResponse(userData, isUser);
const products = parseResponse(productData, isProductArray);
const config = parseResponse(configData, isConfig);

Key Takeaway: A generic parseResponse helper centralizes validation logic, letting you pair any validator with any unknown data for type-safe, reusable parsing—throwing errors when data doesn't match expectations.