Skip to content

zod ​

zod is typeScript-first schema validation with static type inference.

Zova encapsulates zod and provides an enhanced version of z object.

Basic usage ​

Create a simple string schema.

typescript
const name = z.string();

Specify as optional.

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

Set default value.

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

Common types ​

string.

typescript
const name = z.string();

number.

typescript
const age = z.number();

boolean.

typescript
const bRead = z.boolean();

bigint.

typescript
const num = z.bigint();

date.

typescript
const birthday = z.date();

object.

typescript
const user = z.object({
  name: z.string().optional(),
  age: z.number().optional(),
});

Enhanced functionality ​

1. Coercion ​

Automatically perform type coercion using the schema generated by z. 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 ​

z 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 = z.object({
  user: z
    .object({
      name: z.string(),
      age: z.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 = z.object({
  colors: z.array(z.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.