Skip to content

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

typescript
const name = zz.string();

Specify as optional

typescript
const name = zz.string().optional();

Set default value

typescript
const name = zz.string().optional().default('');

Common types

string

typescript
const name = zz.string();

number

typescript
const age = zz.number();

boolean

typescript
const bRead = zz.boolean();

bigint

typescript
const num = zz.bigint();

date

typescript
const birthday = zz.date();

object

typescript
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

typescript
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

typescript
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

typescript
export const QuerySchema = zz.object({
  colors: zz.array(zz.string()).optional(),
});

The value of the colors array can be obtained directly in render

typescript
export class RenderCardHeader {
  render() {
    return (
      <div>
        <div>colors: {this.$query.colors?.join(',')}</div>
        <div>length: {this.$query.colors?.length}</div>
      </div>
    );
  }
}

Released under the MIT License.