Function validate

  • The validate function exists in two flavors: a safe, non throwing one, and a throwing one. If the throwing member of the options parameter is set to true, then the validate function will throw an error when the validation fails. In any other case, the validate function will return a Result object, with either the typed, validated data, or the errors encountered during validation.

    Non-throwing version

    Example

    import { validate } from "typerun";
    import { string, number } from "typerun/schema";

    const fail = validate(string)(31);
    console.log(!fail.ok && fail.errors);
    // -> [{ name: "ValidationError", message: "Value `31` is not a string" }]

    const good = validate(number)(42);
    console.log(good.ok && good.data);
    // -> 42

    Type Parameters

    • S

    Parameters

    • schema: Schema<S>

      The schema to validate.

    • Optional options: {
          throwing: false;
      }

      The options of the function.

      • throwing: false

    Returns ((data) => Result<S, ParseError>)

    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.

    Example

      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 }
    // },
    // ]
  • Throwing version

    Example

    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" }]
    }

    Type Parameters

    • S

    Parameters

    • schema: Schema<S>

      The schema to validate.

    • options: {
          throwing: true;
      }

      The options of the function.

      • throwing: true

    Returns ((data) => S)

    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.

      • (data): S
      • Parameters

        • data: unknown

        Returns S