Capítulo 27 de 61

Chapter 27: Pipes

Core Idea

.pipe() chains one schema's output into another schema's input — most useful for feeding a validated value into a transform, and z.input()/z.output() let you reach the input/output side of pipes nested deep inside a larger schema.

Key Concepts

  • schema.pipe(nextSchema) (or z.pipe(schema, nextSchema) in Mini): validates with schema first, then feeds the result into nextSchema.
  • z.input(schema) / z.output(schema): runtime schemas that replace every pipe (including codecs) inside a larger schema with its input or output side — needed because .in/.out accessors don't reach into nested objects/records/maps. Only codecs have two genuinely different sides; z.output() applied to a one-way transform just returns the transform itself.

Code Examples

const stringToLength = z.string().pipe(z.transform(val => val.length));
stringToLength.parse("hello"); // => 5

// reaching a codec nested inside an object
const Event = z.object({ name: z.string(), at: stringToDate }); // stringToDate: a codec

z.input(Event).parse({ name: "launch", at: "2024-01-01T00:00:00Z" }); // ok — expects the ISO string form
z.output(Event).parse({ name: "launch", at: new Date() });            // ok — expects the Date form
  • What it demonstrates: piping a validated string into a length-transform, and using z.input()/z.output() to validate against either side of a codec nested in an object.

Key Takeaways

  1. .pipe() is the composition primitive: validate, then feed forward — it's what makes transforms and codecs useful inside larger schemas.
  2. When a schema with a nested codec/pipe is buried inside an object, record, or map, z.input()/z.output() are the way to validate against its input or output shape — direct .in/.out accessors only work at the top level.

Connects To

  • Transforms: the most common thing piped into.
  • Codecs — Basics: codecs are the two-sided case where z.input()/z.output() matter most.