zod
zod is typeScript-first schema validation with static type inference
Zova encapsulates zod
and provides an enhanced version of zz
object
Basic usage
Create a simple string schema
const name = zz.string();
Specify as optional
const name = zz.string().optional();
Set default value
const name = zz.string().optional().default('');
Common types
string
const name = zz.string();
number
const age = zz.number();
boolean
const bRead = zz.boolean();
bigint
const num = zz.bigint();
date
const birthday = zz.date();
object
const user = zz.object({
name: zz.string().optional(),
age: zz.number().optional(),
});
Enhanced functionality
1. Coercion
Automatically perform type coercion using the schema generated by zz
. Because the Params
and Query
obtained from the route path are of string
type by default, they need to be coerced to the actual target type
2. boolean coercion
zz
performs special processing on boolean, coercing the strings 'false', 'undefined', 'null' or '0' to false
3. Support json object
We can pass json object in Query. For example, we define a user object in Query
export const QuerySchema = zz.object({
user: zz
.json({
name: zz.string(),
age: zz.number(),
})
.optional(),
});
The value of the user object can be obtained directly in render
export class RenderCardHeader {
render() {
return (
<div>
<div>name: {this.$query.user?.name}</div>
<div>age: {this.$query.user?.age}</div>
</div>
);
}
}
4. Support array object
We can pass array object in Query. For example, we define a colors array in Query
export const QuerySchema = zz.object({
colors: zz.array(zz.string()).optional(),
});
The value of the colors array can be obtained directly in render
export class RenderCardHeader {
render() {
return (
<div>
<div>colors: {this.$query.colors?.join(',')}</div>
<div>length: {this.$query.colors?.length}</div>
</div>
);
}
}