Optional Fields and Partial API Data
You'll learn how to safely validate API responses when some properties might be missing or undefined.
The Real-World Problem
When working with external APIs, you can't always guarantee every field will be present. A user profile might have an optional bio, a product might not have a discount, or older API versions might omit newly added fields entirely. If you treat all properties as required when validating unknown data, your application will fail on perfectly valid responses.
The Core Idea
When validating API data typed as unknown, you need type predicates and guards that account for optional properties. This means checking whether a property exists before checking its type, and accepting its absence as valid.
Think of it like a checklist where some items are marked "optional" — you don't fail the whole check just because someone skipped the optional sections.
Validating Optional Properties
Here's how to handle optional fields in your validation:
interface UserProfile {
id: number;
name: string;
email: string;
bio?: string; // Optional field
age?: number; // Optional field
}
function isUserProfile(data: unknown): data is UserProfile {
// First, ensure it's an object
if (typeof data !== 'object' || data === null) {
return false;
}
const obj = data as Record<string, unknown>;
// Check required fields
if (typeof obj.id !== 'number') return false;
if (typeof obj.name !== 'string') return false;
if (typeof obj.email !== 'string') return false;
// Check optional fields: undefined OR the expected type
if (obj.bio !== undefined && typeof obj.bio !== 'string') {
return false;
}
if (obj.age !== undefined && typeof obj.age !== 'number') {
return false;
}
return true;
}
// Usage with fetch
const response = await fetch('/api/user');
const data: unknown = await response.json();
if (isUserProfile(data)) {
console.log(data.name); // Always safe
console.log(data.bio?.toUpperCase()); // Optional chaining for safety
}
The Pattern
For each optional property, your validation logic becomes: "If it's present, it must be the right type. If it's absent, that's fine."
// For optional field `bio?: string`
if (obj.bio !== undefined && typeof obj.bio !== 'string') {
return false; // Present but wrong type = invalid
}
// If bio is undefined, we don't return false = valid
This pattern ensures you reject malformed data while accepting legitimately missing optional fields.
Key Takeaway: When validating unknown API data with optional fields, check that absent properties are undefined OR the correct type — never reject data simply because an optional field is missing.