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 types
  • as casts don't validate

More most-asked TypeScript Developer questions

← All TypeScript Developer questions