Zod Schema Parse With Transform

Define Zod schemas with transforms for input normalization validation and output type inference.

TypescriptForm Validation

Code

typescriptsnippet
1 line
import{z}from'zod';export const userSchema=z.object({email:z.string().email().transform(s=>s.toLowerCase()),age:z.number().int().min(18).max(120),tags:z.array(z.string()).default([]),metadata:z.record(z.string(),z.unknown()).optional()}).strict();export type User=z.infer<typeof userSchema>;export function parseUser(input:unknown):User{return userSchema.parse(input);}export function safeParseUser(input:unknown){const result=userSchema.safeParse(input);return result.success?{valid:true,data:result.data}:{valid:false,errors:result.error.issues};}

How it works

Zod Schema Parse With Transform is built around the functions parseUser and safeParseUser.

From zod it pulls z — the imports name exactly which library surface the snippet touches.

Watch out for

  • Plan for an install step: zod is a real dependency, resolved by the package manager.

Putting it to use

The main signature reads export const userSchema=

The surface worth importing is userSchema; the helpers around it are private to the snippet.

Interactive Tools for This Topic

FAQ

Which packages must be installed first?
Yes. The imports resolve to `zod`, which the package manager must provide.