Skip to content

Instantly share code, notes, and snippets.

@iskenxan
Created January 17, 2022 14:27
Show Gist options
  • Save iskenxan/9a6e3e98fe7771cf2d4afe188aa56b49 to your computer and use it in GitHub Desktop.
Save iskenxan/9a6e3e98fe7771cf2d4afe188aa56b49 to your computer and use it in GitHub Desktop.
Typescript schema validation with zod
import { z } from "zod";
const stringSchema = z.string().nonempty().min(8).max(32);
stringSchema.parse("");
stringSchema.parse(""); // throws an exception
stringSchema.parse("I am a valid password"); // returns "I am a valid password"
const User = z.object({
email: z.string().email(),
name: z.string(),
phoneNumber: z.number()
});
const Hobby = z.object({
hobbyName: z.string().min(1)
});
const Hobbyist = User.merge(Hobby);
const result = Hobbyist.safeParse({
email: "[email protected]",
name: "Hello World",
phoneNumber: 123
});
const result = User.parse({
email: "[email protected]",
name: "Hello World"
});
[
{
"code": "invalid_type",
"expected": "number",
"received": "undefined",
"path": [
"phoneNumber"
],
"message": "Required"
}
]
import { z } from "zod";
const User = z.object({
email: z.string().email(),
name: z.string(),
phoneNumber: z.number()
});
z.string().optional().array(); // (string | undefined)[]
z.string().array().optional(); // string[] | undefined
mySchema.safeParse(""I am a valid password""); // => { success: true; data: "I am a valid password" }
mySchema.safeParse(""); // => { success: false; error: ZodError }
type UserType = z.infer<typeof User>;
[
{
"code": "too_small",
"minimum": 1,
"type": "string",
"inclusive": true,
"message": "Should be at least 1 characters",
"path": []
},
{
"code": "too_small",
"minimum": 8,
"type": "string",
"inclusive": true,
"message": "Should be at least 8 characters",
"path": []
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment