TypeScript Developer interview question · Most asked
Why do you still need runtime validation in TypeScript, and how do libraries like Zod help?
Summary
TypeScript types vanish at runtime, so data from APIs, forms, env vars or JSON.parse isn't actually checked. Schema libraries (Zod, Valibot, ArkType) validate data at runtime and infer static types from the same schema, giving one source of truth.
Longer Answer
Validate at trust boundaries: incoming requests, external API responses, environment variables and local storage. Use safeParse to handle errors without exceptions. Casting (as User) only silences the compiler; it doesn't make data correct.
Code Example
import { z } from "zod";
const UserSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
role: z.enum(["admin", "user"]),
});
type User = z.infer<typeof UserSchema>;
const res = await fetch("/api/me");
const parsed = UserSchema.safeParse(await res.json());
if (!parsed.success) throw new Error("Bad payload");
const user: User = parsed.data;
Key Points
- Types are erased at runtime
- Validate at system boundaries
z.infer<typeof schema>for typesascasts don't validate
More most-asked TypeScript Developer questions
- Explain `any`, `unknown` and `never`.
- What are the differences between `interface` and `type` aliases?
- What is structural typing in TypeScript?
- What is type narrowing and what techniques does TypeScript support?
- What are discriminated unions and why are they powerful?
- What are generics and how do constraints work?
- Which built-in utility types do you use most, and what do they do?
- What is TypeScript and what problems does it solve?