coerce

Coerces the input of a schema to match the required type.

const Schema = coerce<TSchema>(schema, action);

Generics

Parameters

  • schema TSchema
  • action (input: unknown) => unknown

Explanation

coerce can be used to transform an input before it is validated. The function of the action argument is executed at the very beginning of the process, before any other validation is performed. It is therefore perfect for enforcing a specific data type using the built-in data type objects like Boolean, String, Number and Date.

To transform the input at the very end of the process, after all other validations have been performed, use the transform method.

Returns

  • Schema TSchema

Examples

The following examples show how coerce can be used.

Coerce string input

Schema that coerces a string input.

const StringSchema = coerce(string(), String);

Coerce date input

Schema that coerces a date input.

const DateSchema = coerce(date(), (input) => new Date(input));

The following APIs can be combined with coerce.

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 hyunbinseo
  • GitHub profile picture of caegdeveloper