Libraries
    Preparing search index...

    Class UnionSchemaBuilder<TOptions, TRequired, TNullable, TExplicitType, THasDefault, TExtensions>

    Union schema builder class. Allows to create schemas containing alternatives. E.g. string | number | Date. Use it when you want to define a schema for a value that can be of different types. The type of the value will be determined by the first schema that succeeds validation. Any schema type can be supplied as variant. Which means that you are not limited to primitive types and can construct complex types as well, e.g. object | array.

    NOTE this class is exported only to give opportunity to extend it by inheriting. It is not recommended to create an instance of this class directly. Use union() function instead.

    const schema = union(string('foo')).or(string('bar'));
    const result = schema.validate('foo');
    // result.valid === true
    // result.object === 'foo'
    const schema = union(string('foo')).or(string('bar'));
    const result = schema.validate('baz');
    // result.valid === false
    const schema = union(string('yes')).or(string('no')).or(number(0)).or(number(1));
    // equals to 'yes' | 'no' | 0 | 1 in TS
    const result = schema.validate('yes');
    // result.valid === true
    // result.object === 'yes'

    const result2 = schema.validate(0);
    // result2.valid === true
    // result2.object === 0

    const result3 = schema.validate('baz');
    // result3.valid === false

    const result4 = schema.validate(2);
    // result4.valid === false

    union

    Type Parameters

    • TOptions extends readonly SchemaBuilder<any, any, any, any, any>[]
    • TRequired extends boolean = true
    • TNullable extends boolean = false
    • TExplicitType = undefined
    • THasDefault extends boolean = false
    • TExtensions = {}

    Hierarchy (View Summary)

    Index

    Constructors

    Properties

    "[___hasDefault]": THasDefault

    Type-level brand encoding whether this schema has a default value. Not emitted at runtime — used by input type inference.

    "[___type]": TRequired extends true
        ? TNullable extends true
            ? | (
                TExplicitType extends undefined
                    ? SchemaArrayToUnion<TOptions>
                    : TExplicitType
            )
            | null
            : TExplicitType extends undefined
                ? SchemaArrayToUnion<TOptions>
                : TExplicitType
        :
            | (
                TNullable extends true
                    ? | (
                        TExplicitType extends undefined
                            ? SchemaArrayToUnion<TOptions>
                            : TExplicitType
                    )
                    | null
                    : TExplicitType extends undefined
                        ? SchemaArrayToUnion<TOptions>
                        : TExplicitType
            )
            | undefined

    Type-level brand encoding the inferred type of this schema. Not emitted at runtime — used only by InferType.

    Accessors

    • get "~standard"(): StandardSchemaV1.Props<
          ResolvedSchemaType<TResult, TRequired, TNullable>,
      >

      Standard Schema v1 interface.

      Exposes this schema as a Standard Schema v1 validator, enabling out-of-the-box interoperability with any library that consumes the spec — including tRPC, TanStack Form, React Hook Form, T3 Env, Hono, Elysia, next-safe-action, and 50+ other tools.

      Every SchemaBuilder subclass (all 13 builders) inherits this property automatically — no additional setup required.

      Shape of the returned object:

      • version — always 1 (Standard Schema spec version)
      • vendor'@cleverbrush/schema'
      • validate(value) — synchronous; wraps this builder's own .validate() and converts its result to the Standard Schema Result<Output> format:
        • Success: { value: <validated output> }
        • Failure: { issues: [{ message: string }, …] }

      The returned object is cached after the first access so repeated reads return the same reference (required by the spec).

      Returns StandardSchemaV1.Props<ResolvedSchemaType<TResult, TRequired, TNullable>>

      import { object, string, number } from '@cleverbrush/schema';

      const UserSchema = object({
      name: string().minLength(2),
      email: string().email(),
      age: number().min(18).optional(),
      });

      // Grab the Standard Schema interface
      const std = UserSchema['~standard'];
      // std.version === 1
      // std.vendor === '@cleverbrush/schema'

      const ok = std.validate({ name: 'Alice', email: 'alice@example.com' });
      // { value: { name: 'Alice', email: 'alice@example.com', age: undefined } }

      const fail = std.validate({ name: 'A', email: 'not-an-email' });
      // { issues: [{ message: 'minLength' }, { message: 'email' }] }

      // Pass directly to TanStack Form, T3 Env, tRPC, etc.:
      // validators: { onChange: UserSchema, onBlur: UserSchema }
    • get canSkipPreValidation(): boolean

      Whether preValidateSync can be skipped entirely. True when there are no preprocessors and no validators, so the only work would be the required check and wrapping in a noop transaction — which subclasses can do inline.

      Returns boolean

    • get hasCatch(): boolean

      Whether this schema has a catch/fallback value configured via .catch().

      Returns boolean

    • get hasDefault(): boolean

      Whether this schema has a default value configured via .default(). Exposed for fast-path validation in subclasses.

      Returns boolean

    • get isNullable(): boolean

      Whether null is an accepted value for this schema.

      Returns boolean

    • get isNullRequiredViolation(): boolean

      Null is a legitimate JavaScript value that a union option (e.g. NullSchemaBuilder) may accept. Override the base-class behaviour so that a required union does not reject null during pre-validation; instead, each option gets the opportunity to validate it.

      Returns boolean

    • get isReadonly(): boolean

      Whether this schema is marked as readonly. Type-level only — no runtime enforcement.

      Returns boolean

    • get isRequired(): TRequired

      Whether the schema requires a non-null/non-undefined value.

      Returns TRequired

    • set isRequired(value: boolean): void

      Sets the requirement flag. Must be a boolean.

      Parameters

      • value: boolean

      Returns void

    • get preprocessors(): PreprocessorEntry<TResult>[]

      A list of preprocessors associated with the Builder

      Returns PreprocessorEntry<TResult>[]

    • get requiredErrorMessage(): ValidationErrorMessageProvider

      The error message provider used for the "is required" error. Exposed for fast-path validation in subclasses.

      Returns ValidationErrorMessageProvider

    • get type(): string

      The string identifier of the schema type (e.g. 'string', 'number', 'object').

      Returns string

    • set type(value: string): void

      Sets the schema type identifier. Must be a non-empty string.

      Parameters

      • value: string

      Returns void

    • get validators(): ValidatorEntry<TResult>[]

      A list of validators associated with the Builder

      Returns ValidatorEntry<TResult>[]

    Methods

    • Adds a preprocessor to a preprocessors list

      Parameters

      • preprocessor: Preprocessor<
            TExplicitType extends undefined
                ? SchemaArrayToUnion<TOptions>
                : TExplicitType,
        >
      • Optionaloptions: { mutates?: boolean }

      Returns this

    • Adds a validator to validators list.

      Parameters

      • validator: Validator<
            TExplicitType extends undefined
                ? SchemaArrayToUnion<TOptions>
                : TExplicitType,
        >
      • Optionaloptions: { mutates?: boolean }

      Returns this

    • Sets a fallback value for this schema. When validation fails for any reason, the fallback value is returned as a successful result instead of validation errors.

      This is useful for graceful degradation — for example, providing a safe default when parsing untrusted input that might not conform to the schema.

      Accepts either a static value or a factory function. Factory functions are called each time the fallback is needed (useful for mutable values like () => []).

      Unlike default, which only fires when the input is undefined, .catch() fires on any validation failure — type mismatch, constraint violation, etc.

      When .catch() is set, parse and parseAsync will never throw.

      Parameters

      • value:
            | (
                TExplicitType extends undefined
                    ? SchemaArrayToUnion<TOptions>
                    : TExplicitType
            )
            | (
                () => TExplicitType extends undefined
                    ? SchemaArrayToUnion<TOptions>
                    : TExplicitType
            )

        the fallback value, or a factory function producing the fallback

      Returns this

      const schema = string().catch('unknown');
      schema.validate(42); // { valid: true, object: 'unknown' }
      schema.validate('hello'); // { valid: true, object: 'hello' }
      schema.parse(42); // 'unknown' (no throw)
      // Factory function for mutable fallbacks
      const schema = array(string()).catch(() => []);
      schema.validate(null); // { valid: true, object: [] }
      // Contrast with .default() — default fires only on undefined
      const d = string().default('anon');
      d.validate(undefined); // { valid: true, object: 'anon' } ← fires
      d.validate(42); // { valid: false, errors: [...] } ← does NOT fire

      const c = string().catch('anon');
      c.validate(undefined); // { valid: true, object: 'anon' } ← fires
      c.validate(42); // { valid: true, object: 'anon' } ← also fires
    • Remove all preprocessors for this schema.

      Returns this

    • Remove all validators for this schema.

      Returns this

    • Protected method used to create a new instance of the Builder defined by the props object. Should be used to instantiate new builders to keep builder's immutability.

      Type Parameters

      • T extends readonly SchemaBuilder<any, any, any, any, any>[]
      • TReq extends boolean

      Parameters

      • props: UnionSchemaBuilderCreateProps<T, TReq>

        arbitrary props object

      Returns this

    • Attaches a human-readable description to this schema as runtime metadata.

      The description has no effect on validation — it is purely informational. It is accessible via .introspect().description and is emitted as the description field by toJsonSchema() from @cleverbrush/schema-json.

      Useful for documentation generation, form labels, and AI tool descriptions.

      Parameters

      • text: string

      Returns this

      const schema = object({
      name: string().describe('The user\'s full name'),
      age: number().optional().describe('Age in years'),
      }).describe('A user object');

      schema.introspect().description; // 'A user object'
    • Internal

      Retrieves extension metadata by key. Used by extension authors inside defineExtension() callbacks.

      Parameters

      • key: string

      Returns unknown

    • Generates a serializable object describing the defined schema

      Returns {
          catchValue:
              | (
                  TExplicitType extends undefined
                      ? SchemaArrayToUnion<TOptions>
                      : TExplicitType
              )
              | (
                  () => TExplicitType extends undefined
                      ? SchemaArrayToUnion<TOptions>
                      : TExplicitType
              )
              | undefined;
          defaultValue:
              | (
                  TExplicitType extends undefined
                      ? SchemaArrayToUnion<TOptions>
                      : TExplicitType
              )
              | (
                  () => TExplicitType extends undefined
                      ? SchemaArrayToUnion<TOptions>
                      : TExplicitType
              )
              | undefined;
          description: string | undefined;
          extensions: { [key: string]: unknown };
          hasCatch: boolean;
          hasDefault: boolean;
          isNullable: boolean;
          isReadonly: boolean;
          isRequired: boolean;
          options: TOptions;
          preprocessors: readonly PreprocessorEntry<
              TExplicitType extends undefined
                  ? SchemaArrayToUnion<TOptions>
                  : TExplicitType,
          >[];
          requiredValidationErrorMessageProvider: ValidationErrorMessageProvider<
              SchemaBuilder<any, any, any, any, any>,
          >;
          type: string;
          validators: readonly ValidatorEntry<
              TExplicitType extends undefined
                  ? SchemaArrayToUnion<TOptions>
                  : TExplicitType,
          >[];
      }

      • catchValue:
            | (
                TExplicitType extends undefined
                    ? SchemaArrayToUnion<TOptions>
                    : TExplicitType
            )
            | (
                () => TExplicitType extends undefined
                    ? SchemaArrayToUnion<TOptions>
                    : TExplicitType
            )
            | undefined

        The catch/fallback value or factory function set via .catch().

      • defaultValue:
            | (
                TExplicitType extends undefined
                    ? SchemaArrayToUnion<TOptions>
                    : TExplicitType
            )
            | (
                () => TExplicitType extends undefined
                    ? SchemaArrayToUnion<TOptions>
                    : TExplicitType
            )
            | undefined

        The default value or factory function.

      • description: string | undefined

        The human-readable description attached to this schema via .describe(), or undefined if none was set.

      • extensions: { [key: string]: unknown }

        Extension metadata. Stores custom state set by schema extensions.

      • hasCatch: boolean

        Whether a catch/fallback value has been set on this schema via .catch().

      • hasDefault: boolean

        Whether a default value (or factory) has been set on this schema.

      • isNullable: boolean

        If set to true, schema values of null are considered valid.

      • isReadonly: boolean

        If set to true, the inferred type is marked as readonly. Type-level only — no runtime enforcement.

      • isRequired: boolean

        If set to false, schema will be optional (null or undefined values will be considered as valid).

      • options: TOptions

        Array of schemas participating in the union.

      • preprocessors: readonly PreprocessorEntry<
            TExplicitType extends undefined
                ? SchemaArrayToUnion<TOptions>
                : TExplicitType,
        >[]

        Array of preprocessor functions

      • requiredValidationErrorMessageProvider: ValidationErrorMessageProvider<SchemaBuilder<any, any, any, any, any>>

        Custom error message provider for the 'is required' validation error.

      • type: string

        String id of schema type, e.g. string', numberorobject`.

      • validators: readonly ValidatorEntry<
            TExplicitType extends undefined
                ? SchemaArrayToUnion<TOptions>
                : TExplicitType,
        >[]

        Array of validator functions

    • Synchronously validates the value and returns it if valid. Throws a SchemaValidationError if validation fails.

      Parameters

      • object: any

        the value to parse

      • Optionalcontext: ValidationContext<SchemaBuilder<any, any, any, any, {}>>

        optional validation context

      Returns TExplicitType extends undefined ? SchemaArrayToUnion<TOptions> : TExplicitType

      the validated value

      SchemaValidationError if validation fails

      Error if the schema contains async preprocessors, validators, or error message providers

    • Asynchronously validates the value and returns it if valid. Throws a SchemaValidationError if validation fails.

      Parameters

      • object: any

        the value to parse

      • Optionalcontext: ValidationContext<SchemaBuilder<any, any, any, any, {}>>

        optional validation context

      Returns Promise<
          TExplicitType extends undefined
              ? SchemaArrayToUnion<TOptions>
              : TExplicitType,
      >

      the validated value

      SchemaValidationError if validation fails

    • Parameters

      • object: any
      • Optionalcontext: ValidationContext<SchemaBuilder<any, any, any, any, {}>>

      Returns Promise<PreValidationResult<any, { validatedObject: any }>>

      Use preValidateAsync instead. This alias will be removed in a future version.

    • Async version of pre-validation. Runs preprocessors, validators, and the required/optional check on object. Supports async preprocessors, validators, and error message providers.

      Parameters

      • object: any

        the value to pre-validate

      • Optionalcontext: ValidationContext<SchemaBuilder<any, any, any, any, {}>>

        optional validation context settings

      Returns Promise<PreValidationResult<any, { validatedObject: any }>>

      a PreValidationResult containing the preprocessed transaction, context, and any errors

    • Synchronous version of preValidateAsync. Throws at runtime if any preprocessor or validator returns a Promise.

      Parameters

      • object: any

        the value to pre-validate

      • Optionalcontext: ValidationContext<SchemaBuilder<any, any, any, any, {}>>

        optional validation context settings

      Returns PreValidationResult<any, { validatedObject: any }>

      a PreValidationResult containing the preprocessed transaction, context, and any errors

      Error if a preprocessor or validator returns a Promise (use preValidateAsync instead)

    • Perform asynchronous schema validation on object. Supports async preprocessors, validators, and error message providers.

      If a fallback has been set via catch, a failed validation result is replaced by a successful result built from the fallback value, preserving the specialized result shape (e.g. getErrorsFor / getNestedErrors methods).

      Parameters

      • object: TExplicitType extends undefined ? SchemaArrayToUnion<TOptions> : TExplicitType

        Object to validate

      • Optionalcontext: ValidationContext

        Optional ValidationContext settings

      Returns Promise<
          UnionSchemaValidationResult<
              TExplicitType extends undefined
                  ? SchemaArrayToUnion<TOptions>
                  : TExplicitType,
              TOptions,
          >,
      >

    • Internal

      Sets extension metadata by key. Returns a new schema instance with the extension data stored. The data survives fluent chaining. Used by extension authors inside defineExtension() callbacks.

      Parameters

      • key: string
      • value: unknown

      Returns this