first commit

This commit is contained in:
2026-05-29 08:20:56 +01:00
commit 949299f58d
6368 changed files with 527176 additions and 0 deletions

View File

@@ -0,0 +1,68 @@
# OptionalSchema
<!-- begin:auto-docs -->
_(no submodules)_
<!-- end:auto-docs -->
## Purpose
`OptionalSchema<T>` wraps an inner schema so that `undefined` passes through without validation. Any other value is delegated to the inner schema. It is the canonical way to mark fields as optional in object shapes and as the return type of `.optional()` on any `BaseSchema`.
## Features
- Passes `undefined` through without calling the inner schema
- Delegates all other values to the inner schema
- Composable: `optional(nullable(string()))` is valid
## Usage: Basic Example
```typescript
import { optional, string } from "@suaveplan/validation";
const nickname = optional(string().min(2));
nickname.parse(undefined); // undefined
nickname.parse("Al"); // "Al"
nickname.parse(42); // throws ValidationError
```
## Usage: Advanced Example
```typescript
import { object, string, number, optional } from "@suaveplan/validation";
const ProfileUpdate = object({
displayName: optional(string().min(1).max(50)),
bio: optional(string().max(500)),
age: optional(number().int().min(13)),
});
ProfileUpdate.parse({}); // all optional, empty object valid
```
## API Reference
### `optional<T>(schema: BaseSchema<unknown, T>): OptionalSchema<T>`
Factory wrapping an inner schema.
### `OptionalSchema<T>`
Class extending `BaseSchema<T | undefined, T | undefined>`. The `_parse` method returns `undefined` immediately for `undefined` inputs.
## Implementation Notes
- `OptionalSchema` is also defined in the core `schema.ts` module and re-exported here for convenience.
- `undefined` is the only value that bypasses the inner schema; `null` is not treated as absent (use `nullable()` for that).
### Parse Behaviour
`schema.optional()` wraps any schema so `undefined` is accepted in addition to the underlying type. The inferred output type is `T | undefined`. Object schemas treat missing keys as `undefined`, so `z.object({ x: z.string().optional() }).parse({})` is valid.
## Further Usage: Basic Example
```ts
import z from "@suaveplan/validation";
const s = z.string().optional();
s.parse(undefined); // undefined
```
Internally `.optional()` is a thin wrapper that short-circuits on `undefined` and delegates everything else to the inner schema. Optionality composes cleanly with nullability, defaults, and refinements — the inner transforms only see defined, non-null inputs so their implementations stay simple.