Files
skills/docs/foundation/data/validation/src/schemas/optional/optional.md
2026-05-29 08:20:56 +01:00

2.4 KiB

OptionalSchema

(no submodules)

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

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

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

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.