TypeScript Master (50 Qs)•Part 3: Enterprise Architecture, Compiler Internals & Performance (Senior / Staff)
How does Runtime Validation (Zod) synchronize with Compile-Time TypeScript?
senior LevelCode ExampleFormsPerformanceTypeScript
In Simple Words:
TypeScript types vanish at runtime and cannot validate incoming API payloads from external users.
Zod provides runtime schema validation that automatically infers static TypeScript types using z.infer:
typescript
import { z } from 'zod';
const UserSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
role: z.enum(['admin', 'user']),
});
// Infer static compile-time TypeScript type from runtime schema
export type User = z.infer<typeof UserSchema>;
// Validate incoming API request at runtime
export function handlePost(data: unknown): User {
return UserSchema.parse(data); // Throws at runtime if invalid, returns typed User
}