Typed unique collections
Validate collections of identifiers, tags, or other unique primitive values at an API boundary.
Zod · Module
z.set(element) creates a Zod schema for native JavaScript Set values, validating each member with the supplied element schema. Set schemas support cardinality constraints such as nonempty, min, max, and size.
Call z.set with an element schema to validate native JavaScript Set values. The resulting schema checks every member against that schema and can impose collection-size constraints such as nonempty, min, max, or exact size.
z.set(element)| Name | Type | Description |
|---|---|---|
element | Zod schema | Zod schema used to validate every member of the Set. |
A Zod schema representing a native Set whose members conform to the supplied element schema.
import { z } from "zod";
const UserIds = z.set(z.string()).min(1);
const result = UserIds.safeParse(new Set(["u1", "u2"]));
if (result.success) {
console.log(result.data); // Set<string>
}Creates a non-empty set schema whose elements must be strings, then safely validates a native Set.
Validate collections of identifiers, tags, or other unique primitive values at an API boundary.
Enforce minimum, maximum, or exact membership counts for a Set.
Expose an immutable inferred collection type after validation.
z.set(elementSchema) creates a schema for a native Set whose members are validated by elementSchema. For example, z.set(z.number()) infers Set<number> and accepts a Set containing numbers.
Follow-up: How would you require at least five members? Use z.set(elementSchema).min(5), which applies a lower bound to the Set size.
The element schema determines the type each Set member must satisfy, while the Set schema can additionally constrain cardinality. A string Set can therefore be modeled with z.set(z.string()).
Follow-up: How do you require exactly five members? Add .size(5) to the Set schema.
Zod provides nonempty, min, max, and size for Set cardinality. These express at least one member, minimum size, maximum size, or an exact size respectively.
Follow-up: What TypeScript type does readonly produce here? z.set(z.string()).readonly() produces ReadonlySet<string>.
z.mapz.arrayz.infernonemptyminmaxsizereadonly