The record
schema checks that the type of the value is an object, and that all of its keys
match the given schema, as well as all of its values.
import { record, value, number, either } from "typerun/schema";
import { is } from "typerun";
const schema = record({ k: either(value("a"), value("b")), v: number });
if (is(schema)({ a: 42, b: 31 })) {
console.log("value is an object with numbers");
}
if (!is(schema)({ a: 42, b: "hello" })) {
console.log("value is not an object with numbers");
}
if (!is(schema)({ a: 42, c: 93 })) {
console.log("value is not an object with correct keys");
}
The
record
schema checks that the type of the value is an object, and that all of its properties match the given schema(s). This schema exists in two flavors: one where the keys are strings, and one where the keys are of a specific type.Defining a record by its values
In this version of
record
, the schema of the values is given as parameter to the function.Example
The schema of the keys cannot be validated using this version, they must simply be valid JavaScript object keys. If you need specific values for the keys, use the second version of the
schema
record.