Function object

  • The object schema checks that the type of the value is an object, and that all of its properties match the given schemas. The properties are defined in a record. The keys of the record are the property names, and the values are the schemas to validate the properties.

    Example

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

    const schema = object({
    name: string,
    age: number,
    });

    if (is(schema)({ name: "John", age: 42 })) {
    console.log("value is an object with a name and an age");
    }
    if (!is(schema)({ name: "John", age: "42" })) {
    console.log("value is not an object with a name and an age");
    }

    If you use the validate function, the errors contain all of the different type validation fails from the object.

    Objects can be combined with any other schemas, to create complex validation patterns.

    import { object, optional, either, string, number, array } from "typerun/schema";
    import { is } from "typerun";

    const schema = object({
    name: optional(string),
    property: array(either(object({ name: string, age: number }), string)),
    });

    if (is(schema)({ name: "John", property: [{ name: "John", age: 42 }, "hello"] })) {
    console.log("value matches the schema");
    }
    if (is(schema)({ property: ["a", "b", "c"] })) {
    console.log("value matches the schema");
    }

    Type Parameters

    Parameters

    • schemaRecord: R

      A record of schemas to validate the properties of an object.

    Returns Schema<{
        [k in keyof R]: Infer<R[k]>
    }>