Zod is a TypeScript-first schema validation library where schemas serve dual purpose: runtime validation and static type inference. Its combinator API supports complex validation patterns including discriminated unions, transformations, custom refinements, and async validation.
0 / 5 completed
1 / 5
A developer defines const schema = z.object({ age: z.number().min(0).max(120) }) and calls schema.parse({ age: -5 }). What happens?
z.parse() throws a ZodError when validation fails, containing a structured array of issues with paths and messages. The min(0) constraint fails for -5 and the error message indicates the minimum value constraint. Use safeParse() to get a result object instead of throwing.
2 / 5
What is the difference between z.infer<typeof schema> and calling schema.parse()?
z.infer<typeof schema> is a TypeScript utility that extracts the static TypeScript type from a Zod schema at compile time — no runtime cost. schema.parse() validates actual runtime data and throws or returns the typed value. Together they provide end-to-end type safety.
3 / 5
A developer uses z.discriminatedUnion('type', [...]) instead of z.union([...]). What performance benefit does this provide?
z.discriminatedUnion() uses a discriminant field (like 'type') to immediately select which union member schema to use, rather than trying each member in sequence. This is O(1) lookup vs O(n) for regular z.union(), making it significantly faster for unions with many members.
4 / 5
Which Zod method allows transforming validated data into a different shape or type?
.transform() in Zod takes a callback that receives the validated value and returns a new value of any type. For example, z.string().transform(s => s.toUpperCase()) validates that the input is a string and then uppercases it. The output type is inferred from the transform callback.
5 / 5
A developer needs to validate that a string is a valid URL and also check that it uses HTTPS. Which Zod pattern correctly achieves this?
.refine() adds custom validation logic after built-in validators. Combining z.string().url() (validates URL format) with .refine(url => url.startsWith('https://')) checks both format and protocol. The second argument to refine() is the error message or options object.