SponsorsTable of ContentsGetting StartedInstallationMigration guide
Usage
CoerceLiteralsStringsNumbersBigIntsNaNsBooleansDatesEnumsOptionalsNullablesObjectsArraysUnionsRecordsMapsSetsIntersectionsRecursive typesPromisesInstanceofFunctionsPreprocess
Schema methods
Custom schemas
Guides and Concepts
Error HandlingComparisonEcosystem
Contributing
ChangelogCode of ConductLICENSE
Links
Clerk
⌘+J

© 2025 Zod


Designed in Earth-616

Build by oeri

Functions

Zod also lets you define "function schemas". This makes it easy to validate the inputs and outputs of a function without intermixing your validation code and "business logic".

You can create a function schema with z.function(args, returnType) .

const myFunction = z.function();
 
type myFunction = z.infer<typeof myFunction>;
// => ()=>unknown

Define inputs and outputs.

const myFunction = z
  .function()
  .args(z.string(), z.number()) // accepts an arbitrary number of arguments
  .returns(z.boolean());
 
type myFunction = z.infer<typeof myFunction>;
// => (arg0: string, arg1: number)=>boolean

Function schemas have an .implement() method which accepts a function and returns a new function that automatically validates its inputs and outputs.

const trimmedLength = z
  .function()
  .args(z.string()) // accepts an arbitrary number of arguments
  .returns(z.number())
  .implement(x => {
    // TypeScript knows x is a string!
    return x.trim().length;
  });
 
trimmedLength("sandwich"); // => 8
trimmedLength(" asdf "); // => 4

If you only care about validating inputs, just don't call the .returns() method. The output type will be inferred from the implementation.

You can use the special z.void() option if your function doesn't return anything. This will let Zod properly infer the type of void-returning functions. (Void-returning functions actually return undefined.)

const myFunction = z
  .function()
  .args(z.string())
  .implement(arg => {
    return [arg.length];
  });
 
myFunction; // (arg: string)=>number[]

Extract the input and output schemas from a function schema.

myFunction.parameters();
// => ZodTuple<[ZodString, ZodNumber]>
 
myFunction.returnType();
// => ZodBoolean

On This Page

Functions

Edit this page on GitHub