Expose a subset of fields
Create a public response schema from a larger internal object while retaining only approved fields.
Zod · Module
.pick derives a new Zod object schema containing only selected properties from an existing object schema. Provide a mask with the keys to retain set to true.
For a Zod object schema, .pick creates a new schema containing only the properties whose keys are enabled in the selection object. The resulting schema can then validate data and provide a narrowed inferred TypeScript shape.
schema.pick(mask)| Name | Type | Description |
|---|---|---|
mask | object mask | An object-shaped key selection in which properties set to true are retained in the derived object schema. |
A new Zod object schema containing the selected keys.
.pick mirrors TypeScript's Pick concept, letting you derive a smaller runtime-validation schema from an existing Zod object schema..pick when a derived schema should expose and validate only a selected subset of an object's properties.true to retain that property in the new schema.import { z } from "zod";
const Recipe = z.object({
title: z.string(),
description: z.string().optional(),
ingredients: z.array(z.string()),
});
const TitleOnly = Recipe.pick({ title: true });
console.log(TitleOnly.parse({ title: "Pasta" }));
Creates an object schema that retains only the selected title property and validates matching input.
Create a public response schema from a larger internal object while retaining only approved fields.
Build a focused validation schema for a form or endpoint that needs only selected properties.
Keep runtime validation and inferred TypeScript types aligned when deriving narrower object contracts.
.pick method do?.pick returns a modified object schema that keeps only the selected keys. It is analogous to TypeScript's built-in Pick utility type and can be used to derive a narrower validated shape.
Follow-up: How would you create the inverse shape? Use .omit to remove specified keys instead of listing the keys to retain.
Call .pick with an object whose selected property values are true, such as Recipe.pick({ title: true }). The returned schema contains the selected property and retains its original validator.
Follow-up: How can the resulting TypeScript type be obtained? Infer it from the returned schema with z.infer<typeof TitleOnly>.
.pick useful in schema design?The method is available on Zod object schemas and is intended for selecting certain keys from an existing schema. The resulting schema validates the selected object shape rather than requiring the original schema's other properties.
Follow-up: What related operation preserves all keys except a chosen set? Use .omit with the keys to exclude.
.omitz.objectz.infer