00
:
00
:
00
:
00
Corso SEO AI - Usa SEOEMAIL al checkout per il 30% di sconto

Array e Tuple

z.array()

Per validare un array, definisci lo schema degli elementi al suo interno.

import { z } from "zod";

// Array di stringhe
const stringhe = z.array(z.string());
stringhe.parse(["ciao", "mondo"]); // OK
stringhe.parse(["ciao", 42]);      // Errore

// Array di numeri
const numeri = z.array(z.number());
numeri.parse([1, 2, 3]); // OK

Puoi anche usare la sintassi equivalente con .array():

// Queste due forme sono identiche
z.array(z.string());
z.string().array();

Validazioni su Array

min, max e length

const almeno3 = z.array(z.string()).min(3, "Servono almeno 3 elementi");
almeno3.parse(["a", "b", "c"]);   // OK
almeno3.parse(["a"]);              // Errore

const massimo5 = z.array(z.number()).max(5, "Massimo 5 elementi");
massimo5.parse([1, 2, 3]);        // OK
massimo5.parse([1, 2, 3, 4, 5, 6]); // Errore

const esatto2 = z.array(z.string()).length(2, "Devono essere esattamente 2");
esatto2.parse(["a", "b"]);        // OK
esatto2.parse(["a"]);             // Errore

nonempty

Garantisce che l’array contenga almeno un elemento. Questo modifica anche il tipo TypeScript inferito.

const nonVuoto = z.array(z.string()).nonempty("L'array non può essere vuoto");
nonVuoto.parse(["ciao"]); // OK
nonVuoto.parse([]);        // Errore

// Il tipo inferito è [string, ...string[]] invece di string[]
type NonVuoto = z.infer<typeof nonVuoto>;
// => [string, ...string[]]

Array di Oggetti

Uno dei pattern più comuni: validare un array di oggetti strutturati.

const ProdottoSchema = z.object({
  id: z.number().int().positive(),
  nome: z.string().min(1),
  prezzo: z.number().positive(),
  disponibile: z.boolean(),
});

const ListaProdotti = z.array(ProdottoSchema);

const dati = ListaProdotti.parse([
  { id: 1, nome: "Tastiera", prezzo: 49.99, disponibile: true },
  { id: 2, nome: "Mouse", prezzo: 29.99, disponibile: false },
]);
// OK: dati è tipizzato come Array<{ id: number; nome: string; ... }>

Combinare Validazioni

const Classifica = z.array(
  z.object({
    giocatore: z.string(),
    punteggio: z.number().int().nonnegative(),
  })
).min(1, "Serve almeno un giocatore")
 .max(100, "Massimo 100 giocatori");

type Classifica = z.infer<typeof Classifica>;

z.tuple()

Le tuple sono array a lunghezza fissa dove ogni posizione ha un tipo specifico.

const coordinata = z.tuple([z.number(), z.number()]);
coordinata.parse([45.4642, 9.1900]); // OK (lat, lng Milano)
coordinata.parse([45.4642]);          // Errore: manca il secondo elemento
coordinata.parse([45.4642, 9.19, 0]); // Errore: troppi elementi

Tuple con Tipi Misti

const record = z.tuple([
  z.string(),   // nome
  z.number(),   // età
  z.boolean(),  // attivo
]);

record.parse(["Marco", 28, true]); // OK
type Record = z.infer<typeof record>;
// => [string, number, boolean]

Tuple con Rest Elements

Puoi aggiungere un tipo “rest” alla fine della tupla per accettare elementi aggiuntivi.

const almeno2Stringhe = z.tuple([z.string(), z.string()]).rest(z.string());
almeno2Stringhe.parse(["a", "b"]);           // OK
almeno2Stringhe.parse(["a", "b", "c", "d"]); // OK
almeno2Stringhe.parse(["a"]);                 // Errore

type AlmenoTwo = z.infer<typeof almeno2Stringhe>;
// => [string, string, ...string[]]

Tuple con Tipi Rest Diversi

// Header fisso + valori numerici variabili
const rigaCsv = z.tuple([z.string(), z.string()]).rest(z.number());

rigaCsv.parse(["Marco", "Rossi", 28, 170, 75]); // OK
type RigaCsv = z.infer<typeof rigaCsv>;
// => [string, string, ...number[]]

Esempio Pratico: Matrice

const RigaSchema = z.array(z.number()).length(3);
const MatriceSchema = z.array(RigaSchema).length(3);

// Matrice 3x3
MatriceSchema.parse([
  [1, 0, 0],
  [0, 1, 0],
  [0, 0, 1],
]); // OK: matrice identità

MatriceSchema.parse([
  [1, 0],
  [0, 1],
]); // Errore: righe di lunghezza 2, non 3

z.set()

Zod supporta anche i Set di JavaScript:

const stringSet = z.set(z.string());
stringSet.parse(new Set(["a", "b", "c"])); // OK

const numSet = z.set(z.number()).min(1).max(10);
numSet.parse(new Set([1, 2, 3])); // OK
numSet.parse(new Set());          // Errore: min 1