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:
- Takes
unknowninput (API response) - Takes a validator function (type predicate)
- Returns strongly typed data if valid
- 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 Ttells TypeScript "if this returns true, narrow toT" - Safe narrowing: Inside the
if, TypeScript knowsdataisT, so the return is type-safe - Fail loudly: The
throwensures 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.