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

2.1 KiB

TupleSchema

(no submodules)

Purpose

TupleSchema<T> validates fixed-length arrays where each positional element has its own schema. Unlike ArraySchema (homogeneous elements), TupleSchema is heterogeneous: position 0 can be a string, position 1 a number, etc. It strictly enforces both the array type and the exact length.

Features

  • Type check: rejects non-arrays with VALIDATION.INVALID_TYPE
  • Length check: rejects arrays with wrong length with VALIDATION.INVALID_TYPE
  • Per-position schema validation with positional error paths

Usage: Basic Example

import { tuple, string, number } from "@suaveplan/validation";

const coord = tuple([number(), number()]);
coord.parse([48.8566, 2.3522]); // [48.8566, 2.3522]
coord.parse([48.8566]); // throws (wrong length)

Usage: Advanced Example

import { tuple, string, number, boolean } from "@suaveplan/validation";

// CSV row parser: [id, name, score, active]
const row = tuple([string().uuid(), string().min(1), number(), boolean()]);

const result = row.safeParse(["550e8400-e29b-41d4-a716-446655440000", "Alice", 99, true]);

API Reference

tuple<T extends AnySchema[]>(schemas: T): TupleSchema<T>

Factory accepting an ordered array of schemas.

_parse(input, ctx): TupleOutputs<T> | INVALID

Validates input is an array of the exact expected length, then parses each element against its positional schema.

Implementation Notes

  • Length mismatch is reported as VALIDATION.INVALID_TYPE (no dedicated TUPLE code) with a descriptive message including both expected and actual lengths.
  • Error paths include the element index: [...parentPath, i].
  • Empty tuples tuple([]) are valid and accept only [].

Parse Behaviour

z.tuple([a, b, c]) validates fixed-length arrays where each position has a distinct schema. Extra trailing items are rejected unless you add a rest element with .rest(schema). Inferred output is a typed tuple ([A, B, C]) rather than an array, so downstream destructuring stays fully typed.