Zod
Basic
ts
import * as z from 'zod'
const SampleSchema = z.object({
a: z.string(),
b: z.string(),
c: z.string(),
})
const valid = SampleSchema.safeParse({
a: '1',
b: '2',
c: '3',
})
// { success: true, data: { a: '1', b: '2', c: '3' } }
console.log(valid)
Filter
ts
import * as z from 'zod'
const SampleSchema = z.object({
a: z.string(),
b: z.string(),
c: z.string(),
})
const valid = SampleSchema.safeParse({
a: '1',
b: '2',
c: '3',
d: '4',
e: '5',
})
// { success: true, data: { a: '1', b: '2', c: '3' } }
console.log(valid)
Failed
ts
import * as z from 'zod'
const SampleSchema = z.object({
a: z.string(),
b: z.string(),
c: z.string(),
})
const valid = SampleSchema.safeParse({
b: '2',
c: '3',
})
// {
// success: false,
// error: ZodError: [
// {
// "expected": "string",
// "code": "invalid_type",
// "path": [
// "a"
// ],
// "message": "Invalid input: expected string, received undefined"
// }
// ]
// ...
// }
console.log(valid)
strictObject
ts
import * as z from 'zod'
const SampleSchema = z.strictObject({
a: z.string(),
b: z.string(),
c: z.string(),
})
const valid = SampleSchema.safeParse({
a: '1',
b: '2',
c: '3',
})
// { success: true, data: { a: '1', b: '2', c: '3' } }
console.log(valid)
Failed
ts
import * as z from 'zod'
const SampleSchema = z.strictObject({
a: z.string(),
b: z.string(),
c: z.string(),
})
const valid = SampleSchema.safeParse({
b: '2',
c: '3',
})
// {
// success: false,
// error: ZodError: [
// {
// "expected": "string",
// "code": "invalid_type",
// "path": [
// "a"
// ],
// "message": "Invalid input: expected string, received undefined"
// }
// ]
// ...
// }
console.log(valid)
ts
import * as z from 'zod'
const SampleSchema = z.strictObject({
a: z.string(),
b: z.string(),
c: z.string(),
})
const valid = SampleSchema.safeParse({
a: '1',
b: '2',
c: '3',
d: '4',
})
// {
// success: false,
// error: ZodError: [
// {
// "code": "unrecognized_keys",
// "keys": [
// "d"
// ],
// "path": [],
// "message": "Unrecognized key: \"d\""
// }
// ]
// ...
// }
console.log(valid)
looseObject
ts
import * as z from 'zod'
const SampleSchema = z.looseObject({
a: z.string(),
b: z.string(),
c: z.string(),
})
const valid = SampleSchema.safeParse({
a: '1',
b: '2',
c: '3',
d: '4',
})
// { success: true, data: { a: '1', b: '2', c: '3', d: '4' } }
console.log(valid)
Failed
ts
import * as z from 'zod'
const SampleSchema = z.looseObject({
a: z.string(),
b: z.string(),
c: z.string(),
})
const valid = SampleSchema.safeParse({
b: '2',
c: '3',
d: '4',
})
// {
// success: false,
// error: ZodError: [
// {
// "expected": "string",
// "code": "invalid_type",
// "path": [
// "a"
// ],
// "message": "Invalid input: expected string, received undefined"
// }
// ]
// ...
// }
console.log(valid)