exactOptionalAsync

Creates an exact optional schema.

const Schema = v.exactOptionalAsync<TWrapped, TDefault>(wrapped, default_);

Generics

Parameters

  • wrapped TWrapped
  • default_ TDefault

Explanation

With exactOptionalAsync the validation of your schema will pass missing object entries, and if you specify a default_ input value, the schema will use it if the object entry is missing. For this reason, the output type may differ from the input type of the schema.

The difference to optionalAsync is that this schema function follows the implementation of TypeScript's exactOptionalPropertyTypes configuration and only allows missing but not undefined object entries.

Returns

Examples

The following examples show how exactOptionalAsync can be used.

New user schema

Schema to validate new user details.

import { isEmailUnique, isUsernameUnique } from '~/api';

const NewUserSchema = v.objectAsync({
  email: v.pipeAsync(
    v.string(),
    v.email(),
    v.checkAsync(isEmailUnique, 'The email is not unique.')
  ),
  username: v.exactOptionalAsync(
    v.pipeAsync(
      v.string(),
      v.nonEmpty(),
      v.checkAsync(isUsernameUnique, 'The username is not unique.')
    )
  ),
  password: v.pipe(v.string(), v.minLength(8)),
});

/*
  The input and output types of the schema:
    {
      email: string;
      password: string;
      username?: string;
    }
*/

Unwrap exact optional schema

Use unwrap to undo the effect of exactOptionalAsync.

import { isUsernameUnique } from '~/api';

const UsernameSchema = v.unwrap(
  // Assume this schema is from a different file and is reused here
  v.exactOptionalAsync(
    v.pipeAsync(
      v.string(),
      v.nonEmpty(),
      v.checkAsync(isUsernameUnique, 'The username is not unique.')
    )
  )
);

The following APIs can be combined with exactOptionalAsync.

Schemas

Methods

Actions

Utils

Async

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 @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 @UniquePixels
  • GitHub profile picture of @jdgamble555
  • GitHub profile picture of @nickytonline
  • GitHub profile picture of @KubaJastrz
  • GitHub profile picture of @andrewmd5
  • GitHub profile picture of @caegdeveloper
  • GitHub profile picture of @dslatkin
  • GitHub profile picture of @BrianCurliss