Object
By default, the object
schema will raise errors if it comes across unrecognised keys during parsing. This behaviour
can be changed with strip
and passthrough
.
Example
import * as p from '@vbudovski/paseri';
const schema = p.object({ foo: p.string(), bar: p.number(),});const data = { foo: 'baz', bar: 123, other: 'something'};
const result = schema.safeParse(data);if (!result.ok) { // result.issue flags `other` as unrecognised.}
Playground
Validators
strict
This is the default behaviour. Errors are raised for any unrecognised keys in the data.
import * as p from '@vbudovski/paseri';
const schema = p .object({ foo: p.string(), bar: p.number(), }) .strict();const data = { foo: 'baz', bar: 123, other: 'something'};
const result = schema.safeParse(data);if (!result.ok) { // result.issue flags `other` as unrecognised.}
strip
Unrecognised keys are stripped from the parsed value.
import * as p from '@vbudovski/paseri';
const schema = p .object({ foo: p.string(), bar: p.number(), }) .strip();const data = { foo: 'baz', bar: 123, other: 'something'};
const result = schema.safeParse(data);if (result.ok) { // result.value typed as `{foo: string; bar: number}`. // `other` is stripped from `result.value`.}
passthrough
Unrecognised keys are preserved in the parsed value.
import * as p from '@vbudovski/paseri';
const schema = p .object({ foo: p.string(), bar: p.number(), }) .passthrough();const data = { foo: 'baz', bar: 123, other: 'something'};
const result = schema.safeParse(data);if (result.ok) { // result.value typed as `{foo: string; bar: number}`. // `other` is preserved in `result.value`.}
Methods
merge
Combine the keys of this schema, and the keys of another schema into a new schema containing both sets of keys. The keys of the second schema will replace the keys of the first schema if there is any overlap. The combined schema will also inherit the behaviour of the second schema for any unknown keys.
import * as p from '@vbudovski/paseri';
const schema1 = p.object({ foo: p.string(), bar: p.number(),}).strict();const schema2 = p.object({ bar: p.string(), baz: p.number(),}).passthrough();const combinedSchema = schema1.merge(schema2);/*The resulting schema will be:p.object({ foo: p.string(), bar: p.string(), baz: p.number(),}).passthrough();*/
pick
Analogous to TypeScript’s built-in Pick
utility type. Creates a schema that contains only the selected keys.
import * as p from '@vbudovski/paseri';
const schema = p.object({ foo: p.string(), bar: p.number(),});const schemaPicked = schema.pick('foo');/*The resulting schema will be:p.object({ foo: p.string(),});*/
omit
Analogous to TypeScript’s built-in Omit
utility type. Creates a schema that contains all except the selected keys.
import * as p from '@vbudovski/paseri';
const schema = p.object({ foo: p.string(), bar: p.number(),});const schemaOmitted = schema.omit('foo');/*The resulting schema will be:p.object({ bar: p.number(),});*/