lazy

Creates a lazy schema.

const Schema = v.lazy<TGetter>(getter);

Generics

Parameters

  • getter TGetter

Explanation

The getter function is called lazily to retrieve the schema. This is necessary to be able to access the input through the first argument of the getter function and to avoid a circular dependency for recursive schemas.

Returns

Examples

The following examples show how lazy can be used.

Binary tree schema

Recursive schema to validate a binary tree.

Due to a TypeScript limitation, the input and output types of recursive schemas cannot be inferred automatically. Therefore, you must explicitly specify these types using BaseSchema.

type BinaryTree = {
  element: string;
  left: BinaryTree | null;
  right: BinaryTree | null;
};

const BinaryTreeSchema: v.GenericSchema<BinaryTree> = v.object({
  element: v.string(),
  left: v.nullable(v.lazy(() => BinaryTreeSchema)),
  right: v.nullable(v.lazy(() => BinaryTreeSchema)),
});

Lazy union schema

Schema to validate a discriminated union of objects.

In most cases, union and variant are the better choices for creating such a schema. I recommend using lazy only in special cases.

const LazyUnionSchema = v.lazy((input) => {
  if (input && typeof input === 'object' && 'type' in input) {
    switch (input.type) {
      case 'email':
        return v.object({
          type: v.literal('email'),
          email: v.pipe(v.string(), v.email()),
        });
      case 'url':
        return v.object({
          type: v.literal('url'),
          url: v.pipe(v.string(), v.url()),
        });
      case 'date':
        return v.object({
          type: v.literal('date'),
          date: v.pipe(v.string(), v.isoDate()),
        });
    }
  }
  return v.never();
});

The following APIs can be combined with lazy.

Schemas

Methods

Actions

Utils

Contributors

Thanks to all the contributors who helped make this page better!

  • GitHub profile picture of fabian-hiller

Partners

Thanks to our partners who support the project ideally and financially.

Sponsors

Thanks to our GitHub sponsors who support the project financially.

  • GitHub profile picture of Thanaen
  • GitHub profile picture of KATT
  • GitHub profile picture of osdiab
  • GitHub profile picture of ruiaraujo012
  • GitHub profile picture of hyunbinseo
  • GitHub profile picture of F0rce
  • GitHub profile picture of caegdeveloper