<vetted />
TypeScript
Mid-Level
Question 3 of 8

How do you make sure your types match what your API actually returns?

Quick Answer

Use runtime validation libraries like Zod, Yup, or io-ts to validate API responses and generate TypeScript types from the schemas.

Detailed Answer5 paragraphs

TypeScript types only exist at compile time—they're erased when code runs. This means data from external sources (APIs, user input, files) isn't actually type-checked at runtime. You need validation.

Zod is the most popular solution. Define a schema that describes your data structure, then use it to both validate data and infer TypeScript types. const UserSchema = z.object({ name: z.string(), age: z.number() }); type User = z.infer<typeof UserSchema>. Parse incoming data with UserSchema.parse(data), which throws on invalid input, or safeParse for error objects.

This approach has several benefits: your types always match your validation logic (single source of truth), you get helpful error messages for invalid data, and you can handle API changes gracefully instead of crashing.

For API clients, validate responses before trusting them. In Next.js or tRPC, Zod integrates naturally for end-to-end type safety. For forms, Zod schemas work with React Hook Form for validated, typed form data.

Other options include Yup (similar to Zod, older), io-ts (more functional approach), and Valibot (lightweight alternative). The key insight: don't trust external data—validate at system boundaries and enjoy type safety within your application.

Key Takeaway

Use runtime validation libraries like Zod, Yup, or io-ts to validate API responses and generate TypeScript types from the schemas.

Ace your interview

Ready to Land Your Dream Job?

Join our network of elite AI-native engineers.