Typed lookup maps
Validate configuration or lookup data represented as a native Map with controlled key and value types.
Zod · Module
z.map() creates a Zod schema for JavaScript Maps by defining separate schemas for keys and values. It infers the corresponding TypeScript Map type and supports entry-count and readonly constraints.
z.map() builds a schema for JavaScript Map instances by taking one schema for keys and another for values. Parsing checks each entry against those schemas and infers the corresponding TypeScript Map type; the resulting map can also be constrained by entry count or made readonly.
z.map(keySchema, valueSchema)| Name | Type | Description |
|---|---|---|
keySchema | ZodType | Schema applied to every key in the Map. |
valueSchema | ZodType | Schema applied to every value in the Map. |
A Zod map schema that validates Map entries and infers a corresponding Map type.
import { z } from "zod";
const StringNumberMap = z.map(z.string(), z.number());
const result = StringNumberMap.parse(
new Map([
["one", 1],
["two", 2],
]),
);
console.log(result.get("one")); // 1Creates a schema for a Map with string keys and numeric values, then validates a matching Map.
Validate configuration or lookup data represented as a native Map with controlled key and value types.
Enforce minimum, maximum, exact, or nonzero entry counts on a Map.
Expose validated map data through a readonly collection type.
z.map(keySchema, valueSchema) defines the validation rules for Map keys and values. For example, z.map(z.string(), z.number()) infers Map<string, number> and validates each map entry.
Follow-up: How would you require at least five entries? Use .min(5) on the map schema; .size(5) would require exactly five.
Pass a key schema first and a value schema second, such as z.map(z.string(), z.number()). Parsing a Map checks that its keys are strings and its values are numbers.
Follow-up: How can the output type be read-only? Add .readonly(), which produces a ReadonlyMap type.
Map schemas support .nonempty(), .min(), .max(), and .size() to constrain the number of entries. These methods respectively require at least one, set a lower bound, set an upper bound, or require an exact count.
Follow-up: What constraint would reject both four and six entries when five are required? Use .size(5).
z.setz.recordz.infernonemptyminmaxsizereadonly