Capítulo 32 de 61
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.
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.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
);
z.function() + .implement() moves argument/return validation out of the function body, so the implementation only deals with already-validated, correctly-typed values.ZodErrors automatically — no manual if/throw boilerplate inside the function.output when you only want input validation and don't need the return value checked.z.function()'s input array behaves like a tuple of parameter schemas.