Handling Nested Objects in API Responses
You'll learn: How to safely validate complex, multi-level API response structures by chaining type guards to progressively narrow unknown data.
The Core Idea
When an API returns deeply nested JSON—like a user profile with an address object containing coordinates—you can't validate the entire structure in one guard. Instead, you chain multiple type guards together, validating one level at a time while TypeScript narrows the type at each step.
Think of it like airport security checkpoints: each level verifies its own structure before allowing you to access deeper properties. You can't check the contents of a suitcase until you've confirmed someone actually has a suitcase.
How It Works
Start with unknown data from your API. Use typeof and in guards to verify the outer object exists and has the expected shape. Once TypeScript narrows that level, repeat the process for nested properties:
function isUserProfile(data: unknown): data is UserProfile {
// First checkpoint: is it an object at all?
if (typeof data !== 'object' || data === null) {
return false;
}
// Second checkpoint: does it have the outer properties?
if (!('name' in data) || typeof data.name !== 'string') {
return false;
}
// Third checkpoint: validate nested address object
if (!('address' in data) || typeof data.address !== 'object' || data.address === null) {
return false;
}
const addr = data.address;
// Fourth checkpoint: properties inside address
if (!('street' in addr) || typeof addr.street !== 'string') {
return false;
}
if (!('coordinates' in addr) || typeof addr.coordinates !== 'object' || addr.coordinates === null) {
return false;
}
const coords = addr.coordinates;
// Fifth checkpoint: deepest level
return (
'lat' in coords && typeof coords.lat === 'number' &&
'lng' in coords && typeof coords.lng === 'number'
);
}
Each guard builds on the previous one's success. You can only safely check data.address.street after confirming data.address exists and is an object.
Key Takeaway: Chain type guards level-by-level to validate nested API structures, verifying each object exists before attempting to access its properties—this progressive narrowing maintains type safety through arbitrarily deep structures.