Skip to the page

TypeScript in real projects · mid

Types vanish at runtime: validating API data

Types are erased, so data from an API, localStorage or a form is unknown at runtime; validate it with a schema (zod, valibot) and derive the type from the schema so the two cannot drift.

The notes

What you must know

  • response.json() returns any/unknown in practice; casting it to User is a lie the compiler can't check.
  • Schema first: const User = z.object({ id: z.string(), age: z.number() }); type User = z.infer<typeof User>.
  • safeParse returns { success: true, data } | { success: false, error } (a discriminated union).
  • Validate at the edges (API responses, env vars, form input), then trust the types inside.

The red pen

Common traps: mistake → fix

  • Mistake: "if the API is typed, the data is safe"

    Fix: the backend can change or send null; only a runtime check proves it.

Easy to hard

Questions interviewers ask, easy to hard

  1. How do you make sure API data matches your TypeScript types?
  2. Where in an app would you validate?
  3. How do you keep schema and type in sync?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview