Unions
Union types, discriminated unions, enums, and type modifiers
Unions
valrs provides comprehensive support for union types, discriminated unions, enums, and type modifiers to handle complex type compositions.
Union
Create a union of multiple schemas with v.union():
Unions try each schema in order and return the first successful match.
Complex Unions
Discriminated Union
For tagged unions with a shared discriminator property, use v.discriminatedUnion():
Discriminated unions provide:
- Better performance: Checks the discriminator first instead of trying all schemas
- Better error messages: Reports invalid discriminator values instead of generic union errors
API Response Pattern
Intersection
Combine multiple schemas with v.intersection():
Extending Types
Literal
Create schemas for exact literal values with v.literal():
Literal Unions
Enum
Create string enum schemas with v.enum():
Enum Object Access
The enum schema provides an enum property for accessing values:
Options Property
Access all enum values via the options property:
Native Enum
Use TypeScript native enums with v.nativeEnum():
Const Enum Alternative
For const enums (which are erased at compile time), use v.enum() instead:
Schema Methods
.or() - Union Method
Create unions using method chaining:
.and() - Intersection Method
Create intersections using method chaining:
Type Modifiers
.optional()
Makes a schema accept undefined:
.nullable()
Makes a schema accept null:
.nullish()
Makes a schema accept both null and undefined:
.default()
Provides a default value when input is undefined:
Supports factory functions for dynamic defaults:
.catch()
Provides a fallback value when parsing fails:
Supports factory functions:
Combining Modifiers
Type Inference
All union types are fully inferred:
Next Steps
- Objects - Object schemas and methods
- Collections - Arrays, tuples, records
- Custom Schemas - Transforms and refinements