3.2 KiB
3.2 KiB
ObjectSchema
(no submodules)
Purpose
ObjectSchema<S> validates plain JavaScript objects against a named-key shape. Each key in the shape is validated against its corresponding schema, and errors carry full dot-path information. Three modes control unknown key handling: strip (default, silently removes extras), strict (rejects extras), and passthrough (copies extras to output). Rich shape-manipulation builders — pick, omit, partial, extend, merge — make it easy to derive new schemas from existing ones without duplication.
All builder methods return new ObjectSchema instances; the original is never modified.
Features
- Type check: rejects non-objects, null, and arrays with
VALIDATION.INVALID_TYPE - Field validation with per-field error paths
- Three unknown-key modes:
strip,strict,passthrough pick(keys)— project to a subset of keysomit(keys)— exclude keyspartial()— make all fields optionalrequired()— return schema as-is (identity, for symmetry)extend(shape)— add/override fieldsmerge(other)— combine with anotherObjectSchema
Usage: Basic Example
import { object, string, number } from "@suaveplan/validation";
const User = object({ name: string(), age: number() });
const user = User.parse({ name: "Alice", age: 30 });
// { name: "Alice", age: 30 }
Usage: Advanced Example
import { object, string, number } from "@suaveplan/validation";
const BaseUser = object({ id: string().uuid(), name: string() });
const AdminUser = BaseUser.extend({ role: string(), level: number().int() });
const PartialUpdate = AdminUser.partial().omit(["id"]);
const update = PartialUpdate.parse({ name: "Bob" });
// { name: "Bob" } — all fields optional, id omitted
const strict = AdminUser.strict();
strict.parse({ id: "...", name: "Alice", role: "admin", level: 1, extra: true });
// throws: Unrecognized key(s): extra
API Reference
object<S extends ObjectShape>(shape: S): ObjectSchema<S>
Factory with default strip mode.
Mode methods (return new ObjectSchema<S>)
strict()— reject unknown keys withVALIDATION.OBJECT.UNRECOGNIZED_KEYSpassthrough()— copy unknown keys to outputstrip()— silently drop unknown keys (default)
Shape manipulation methods
pick<K>(keys: K[]): ObjectSchema<Pick<S, K>>— subset of keysomit<K>(keys: K[]): ObjectSchema<Omit<S, K>>— exclude keyspartial(): ObjectSchema<...>— wrap all values inOptionalSchemarequired(): ObjectSchema<S>— identity (for symmetry withpartial)extend<E>(shape: E): ObjectSchema<S & E>— add/override fieldsmerge<E>(other: ObjectSchema<E>): ObjectSchema<S & E>— merge shapes
Implementation Notes
- Field errors are reported under the field's key path. Nested object errors propagate the full path chain.
partial()wraps each field schema with.optional(), so the output type has all values asT | undefined.passthroughcopies unknown keys before iterating known ones, then known-key parsing runs normally on top.strictchecks for unknown keys using aSetof shape keys — O(n) where n = number of input keys.