Objects
Object schemas with powerful transformation and validation methods
Objects
valrs provides a powerful object schema with methods for transforming shapes, handling unknown keys, and inferring TypeScript types.
Creating Object Schemas
Create object schemas with v.object():
Accessing the Shape
Use .shape to access the underlying shape definition:
Object Methods
extend()
Add new fields to an existing object schema:
merge()
Merge two object schemas together. Properties from the second schema override properties in the first:
pick()
Create a schema with only the specified keys:
omit()
Create a schema without the specified keys:
partial()
Make all fields optional:
This is useful for update operations where you only want to update some fields:
deepPartial()
Make all fields optional recursively, including nested objects:
required()
Make all fields required (removes optional modifiers):
Unknown Key Handling
By default, valrs strips unknown keys from objects. You can change this behavior with these methods:
strip() (default)
Silently removes unknown keys from the output:
passthrough()
Allow unknown keys to pass through without validation:
This is useful when working with APIs that may add new fields:
strict()
Reject any unknown keys with a validation error:
This is useful for strict API validation:
catchall()
Validate unknown keys against a schema:
This is useful for dynamic key-value structures:
keyof()
Get a schema for the literal union of an object's keys:
This is useful for creating type-safe property accessors:
Nested Objects
Objects can be nested to any depth:
Optional Fields
Use .optional() on individual fields:
Default Values
Use .default() to provide default values:
Type Inference Patterns
Input vs Output Types
Some schemas transform values. Use InferInput for input types:
Reusing Schemas
Build complex schemas by composing simpler ones:
Next Steps
- Collections - Arrays, tuples, records, maps, sets
- Unions - Union types, discriminated unions, enums
- Custom Schemas - Refinements and transforms