These libraries validate runtime values with different return, error and transformation contracts. Choose input/output semantics and application integration rather than assuming TypeScript annotations or a successful check normalize all data.
TypeScript annotations do not validate values at runtime. A schema library can check or transform values, but its return and error contract must match what the caller does next.
io-ts codecs decode to an Either-style result, with fp-ts as a peer. The caller handles success and failure rather than assuming decode throws or returns the decoded value directly. Encoding and decoding are distinct directions.
Joi provides schema validation with options and a result containing the validated value and any error. Conversion options affect that value; use the intended output rather than ignoring it and retaining unprocessed input. Its asynchronous validation route has a different promise/error contract. The current package requires Node 20 or newer.
Zod parses data into a successful result or throws, while safeParse returns a discriminated success/error result. Transformations can make the output type differ from the input type, so the type inferred for one side is not automatically the other.
Runtypes distinguishes check, guard, inspect and parse. A check validates and returns the original value; parsing can produce transformed output, including declared-field output for an Object. A successful check is not a promise that data was normalized.
Superstruct supplies assertions and validation results, with create/coercion and mask routes for different output behavior. An assertion and a returned coerced value are different caller contracts. Choose the actual entry and options rather than assuming every operation applies defaults and transformations.
Yup combines schema transforms and validation. Validation can cast unless configured strictly, while explicit casting is not the same as completing all validation rules. Promise-based validation and the resulting value need appropriate caller handling.
Specify missing fields, undefined/null, unknown properties, coercion, defaults and asynchronous checks. These libraries do not share identical defaults or error structures. Test representative input/output pairs and consume structured failures rather than treating human-readable messages as a stable protocol.
A passing schema check does not establish that every later application rule or external operation has completed. Choose the model that makes the application's intended values and failure handling explicit; exchanging schema constructors alone is not a complete migration.
Choose parsing with inferred input/output types and parse/safeParse result handling when that model meets the project requirements.
Choose runtime schemas and detailed validation options when the returned value, conversion settings and errors match the input workflow.
Choose its schema validation and transformation model when casting, asynchronous validation and strictness settings fit the application.
Choose composable structs with explicit assertion, validation and coercion/create routes according to the desired result contract.
Choose a codec and Either-based functional workflow when its decode/encode model and fp-ts integration fit the application.
Choose composable validators with inferred types, distinguishing check/guard/inspect from the transformed output of parse.
TypeScript-first schema validation with static type inference
by @colinhacks
Zod is a TypeScript-first validation library. Define a schema and parse some data with it. You'll get back a strongly typed, validated result.
import * as z from "zod";
const User = z.object({
name: z.string(),
});
// some untrusted data...
const input = {
/* stuff */
};
// the parsed result is validated and type safe!
const data = User.parse(input);
// so you can use it with confidence :)
console.log(data.name);
2kb core bundle (gzipped)npm install zod
Before you can do anything else, you need to define a schema. For the purposes of this guide, we'll use a simple object schema.
import * as z from "zod";
const Player = z.object({
username: z.string(),
xp: z.number(),
});
Given any Zod schema, use .parse to validate an input. If it's valid, Zod returns a strongly-typed deep clone of the input.
Player.parse({ username: "billie", xp: 100 });
// => returns { username: "billie", xp: 100 }
Note — If your schema uses certain asynchronous APIs like async refinements or transforms, you'll need to use the .parseAsync() method instead.
const schema = z.string().refine(async (val) => val.length <= 8);
await schema.parseAsync("hello");
// => "hello"
For hot validation paths, z.compile(schema) returns a schema clone with an ahead-of-time compiled fast path. Valid inputs take the compiled path; invalid inputs fall back to the regular parser so error reporting stays identical.
Across a 55-schema benchmark the median speedup is 2.4x, and it scales with how much work the schema does per parse: a large array of objects is ~9x, a 20-key object ~9x, a nested object ~4.5x, while a bare z.string() gains nothing — compilation removes per-node dispatch and allocation, and a single typeof has none to remove.
const CompiledPlayer = z.compile(Player);
CompiledPlayer.parse({ username: "billie", xp: 100 });
To enable compilation globally for schemas constructed after import:
import "zod/compile"; // place before modules that define schemas
Things to know:
new Function. Global mode is automatically disabled when z.config({ jitless: true }) is set (e.g. CSP environments); calling z.compile() directly is an explicit opt-in.z.compile() hands the schema back unchanged and it keeps using the regular parser, exactly as global mode leaves it. Pass { strict: true } to throw ZodCompileAsyncError / ZodCompileUnsupportedError instead..refine(), .extend(), etc.) returns an uncompiled schema — compile the final schema.See compile docs for details.
When validation fails, the .parse() method will throw a ZodError instance with granular information about the validation issues.
try {
Player.parse({ username: 42, xp: "100" });
} catch (err) {
if (err instanceof z.ZodError) {
err.issues;
/* [
{
expected: 'string',
code: 'invalid_type',
path: [ 'username' ],
message: 'Invalid input: expected string, received number'
},
{
expected: 'number',
code: 'invalid_type',
path: [ 'xp' ],
message: 'Invalid input: expected number, received string'
}
] */
}
}
To avoid a try/catch block, you can use the .safeParse() method to get back a plain result object containing either the successfully parsed data or a ZodError. The result type is a discriminated union, so you can handle both cases conveniently.
const result = Player.safeParse({ username: 42, xp: "100" });
if (!result.success) {
result.error; // ZodError instance
} else {
result.data; // { username: string; xp: number }
}
Note — If your schema uses certain asynchronous APIs like async refinements or transforms, you'll need to use the .safeParseAsync() method instead.
const schema = z.string().refine(async (val) => val.length <= 8);
await schema.safeParseAsync("hello");
// => { success: true; data: "hello" }
Zod infers a static type from your schema definitions. You can extract this type with the z.infer<> utility and use it however you like.
const Player = z.object({
username: z.string(),
xp: z.number(),
});
// extract the inferred type
type Player = z.infer<typeof Player>;
// use it in your code
const player: Player = { username: "billie", xp: 100 };
In some cases, the input & output types of a schema can diverge. For instance, the .transform() API can convert the input from one type to another. In these cases, you can extract the input and output types independently:
const mySchema = z.string().transform((val) => val.length);
type MySchemaIn = z.input<typeof mySchema>;
// => string
type MySchemaOut = z.output<typeof mySchema>; // equivalent to z.infer<typeof mySchema>
// number