Senior LevelJavaScript & TypeScript
How to write type-safe API clients using generic fetch wrappers and zod schema validation?
❓ Interview Prompt: Explain runtime schema validation vs static types, end-to-end type safety, and Zod parse inference.
TypeScript types are erased at runtime. If an external API returns unexpected response formats, static TS types cannot prevent runtime errors!
End-to-End Type Safety Pattern:
Combine Zod runtime schema validation with generic fetch() wrappers. Zod validates incoming API data at runtime and automatically infers the static TypeScript type signature!
Code Implementation Example
typescript
// 1. Define Zod Runtime Schema
const UserSchema = {
parse(data: unknown) {
if (typeof data === 'object' && data !== null && 'id' in data && 'name' in data) {
return data as { id: number; name: string };
}
throw new Error('Invalid API response shape');
}
};
// 2. Generic Fetch Wrapper with Schema Validation
async function apiGet<T>(url: string, validator: { parse: (data: unknown) => T }): Promise<T> {
const response = await fetch(url);
const rawData = await response.json();
return validator.parse(rawData); // Runtime check + static type inference!
}
// 3. Strongly typed & validated call
const user = await apiGet('/api/user/1', UserSchema);
console.log(user.name.toUpperCase()); // Safe at runtime AND compile-time!💡Runtime API schema validation producing guaranteed type-safe response data.
🎯 Interview Key Takeaway
Validate external API responses with runtime schema checkers (like Zod) to enforce static TypeScript guarantees at runtime.
#TypeScript#Validation#API Client#Zod#Senior
Back to all JavaScript & TypeScript Questions→