lazy

Creates a lazy schema.

const Schema = 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: BaseSchema<BinaryTree> = object({
  element: string(),
  left: nullable(lazy(() => BinaryTreeSchema)),
  right: nullable(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 = lazy((input) => {
  if (input && typeof input === 'object' && 'type' in input) {
    switch (input.type) {
      case 'email':
        return object({
          type: literal('email'),
          email: string([email()]),
        });
      case 'url':
        return object({
          type: literal('url'),
          url: string([url()]),
        });
      case 'date':
        return object({
          type: literal('date'),
          date: string([isoDate()]),
        });
    }
  }
  return never();
});

The following APIs can be combined with lazy.

Schemas

Methods

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 dailydotdev
  • GitHub profile picture of ivan-mihalic
  • GitHub profile picture of KATT
  • GitHub profile picture of osdiab
  • GitHub profile picture of Thanaen
  • GitHub profile picture of ruiaraujo012
  • GitHub profile picture of hyunbinseo
  • GitHub profile picture of caegdeveloper