lazy

Creates a lazy schema.

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

Generics

Parameters

  • getter (input: unknown) => TWrapped

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 GenericSchema.

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
  • GitHub profile picture of morinokami
  • GitHub profile picture of EltonLobo07

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 antfu
  • GitHub profile picture of Thanaen
  • GitHub profile picture of osdiab
  • GitHub profile picture of ruiaraujo012
  • GitHub profile picture of hyunbinseo
  • GitHub profile picture of F0rce
  • GitHub profile picture of fabulousgk
  • GitHub profile picture of jdgamble555
  • GitHub profile picture of isoden
  • GitHub profile picture of nickytonline
  • GitHub profile picture of caegdeveloper
  • GitHub profile picture of luckasnix
  • GitHub profile picture of andrew-3kb
  • GitHub profile picture of dslatkin