Capítulo 32 de 61

Chapter 32: Functions

Core Idea

z.function() defines a schema for a function's inputs and output, then .implement() produces a real function that validates both automatically, keeping validation out of business logic.

Key Concepts

  • z.function({ input, output }): input is an array of parameter schemas (or a ZodTuple); output is the return type schema. Omit output to validate inputs only.
  • .implement(fn): wraps fn, returning a new function that validates arguments before calling fn and validates (if output was given) the return value — throws a ZodError on either failure. Inside fn, TypeScript already knows the narrowed input types.
  • .implementAsync(fn): the async counterpart, for functions that return a Promise.

Code Examples

const MyFunction = z.function({
  input: [z.string()],
  output: z.number(),
});

const computeTrimmedLength = MyFunction.implement((input) => {
  return input.trim().length; // TS knows input is string
});

computeTrimmedLength("sandwich"); // => 8
computeTrimmedLength(42);         // throws ZodError — invalid input

const computeTrimmedLengthAsync = MyFunction.implementAsync(
  async (input) => input.trim().length
);
  • What it demonstrates: input/output validation wrapped around a plain function body, with async support.

Key Takeaways

  1. z.function() + .implement() moves argument/return validation out of the function body, so the implementation only deals with already-validated, correctly-typed values.
  2. Validation failures throw ZodErrors automatically — no manual if/throw boilerplate inside the function.
  3. Omit output when you only want input validation and don't need the return value checked.

Connects To

  • Custom: for validating types (including function parameter/return types) that don't fit a standard schema.
  • Tuples: z.function()'s input array behaves like a tuple of parameter schemas.