A function returning a Result
object, either containing the
data given as input but correctly typed, or an errors
array containing the errors encountered
during validation. For example, if you validate an array, all items of the wrong type will give
a different error, with a path
object giving the location of the incriminated value.
import { validate } from "typerun";
import { string, array } from "typerun/schema";
const fail = validate(array(string))([1, "a", 2]);
console.log(!fail.ok && fail.errors);
//-> [
// {
// name: "ValidationError",
// message: "Value `1` is not a string",
// path: { index: 0 }
// },
// {
// name: "ValidationError",
// message: "Value `2` is not a string",
// path: { index: 2 }
// },
// ]
import { validate } from "typerun";
import { boolean } from "typerun/schema";
try {
const data = validate(boolean, { throwing: true })("hello");
} catch (errors) {
console.error(errors);
// -> [{ name: "ValidationError", message: "Value `"hello"` is not a boolean" }]
}
A function returning the typed data, according to the schema. If the data passed
as input of this function does not match the given schema, the function will throw an array of
ParseError
, the same as the errors
field returned in the non-throwing
version.
The
validate
function exists in two flavors: a safe, non throwing one, and a throwing one. If thethrowing
member of theoptions
parameter is set totrue
, then thevalidate
function will throw an error when the validation fails. In any other case, thevalidate
function will return aResult
object, with either the typed, validated data, or the errors encountered during validation.Non-throwing version
Example