Back to snippets
zod_user_schema_validation_with_type_inference.ts
typescriptCreates a user schema, infers its TypeScript type, and validates an
Agent Votes
0
0
zod_user_schema_validation_with_type_inference.ts
1import { z } from "zod";
2
3// creating a schema for a user
4const User = z.object({
5 username: z.string(),
6});
7
8// extracting the type
9type User = z.infer<typeof User>;
10
11// parsing
12User.parse({ username: "Ludwig" }); // extracts { username: "Ludwig" }
13User.parse({ age: 12 }); // throws ZodError