Key Concepts
- Runtime Type Checking: Validating data types at the time the code is executed, not just during compilation.
- Schema Definition: Creating a blueprint that specifies the expected structure and types of data.
- Parsing: The process of validating data against a schema and transforming it into a usable format.
- Safe Parse: A parsing method that returns a success/failure result instead of throwing an error.
- Custom Validators: User-defined functions to enforce specific data constraints beyond basic type checking.
- Data Transformation: Modifying data during the parsing process (e.g., uppercasing a string).
- JSON Schema: A standard format for describing the structure of JSON data, often used in AI applications.
- MCP (Model Composition Protocol): A protocol for defining tools for AI, often using JSON schema for input validation.
- Tree Shaking: A process of removing unused code from a bundle to reduce its size.
- Method Chaining: A style of programming where multiple methods are called on an object in a single line of code.
- Functional Style: A style of programming that emphasizes the use of pure functions and avoids side effects.
The Problem with TypeScript
TypeScript performs type checking at build time, but not at runtime. This means that if external data (e.g., from files, user input, or APIs) doesn't match the expected types, errors can occur during execution, even if the TypeScript code compiled successfully.
- Example: A TypeScript program expects a
phonefield to always be present in a data structure, but the data source sometimes omits this field. TypeScript won't catch this error during compilation, leading to a runtime error like "cannot read properties of undefined."
Introduction to Valibot and Zod
Valibot and Zod are two libraries that provide runtime type checking for JavaScript and TypeScript. They allow you to define schemas that describe the expected structure and types of your data, and then validate data against those schemas at runtime.
Valibot: Schema Definition and Parsing
- Schema Definition: Valibot uses a functional style with the
pipeoperator to combine multiple validations.V.array(V.object(...))defines an array of objects.V.string()validates a string.V.email()validates an email address.V.optional(V.string())defines an optional string.
- Parsing:
V.parse(schema, data)parses data against a schema and throws an error if validation fails.V.safeParse(schema, data)parses data against a schema and returns a success/failure result object.- The result object contains a
successproperty (boolean) and either anoutputproperty (containing the parsed data) or anissuesproperty (containing an array of validation errors).
- The result object contains a
Zod: Schema Definition and Parsing
- Schema Definition: Zod uses method chaining to define schemas.
z.string()validates a string.z.string().email()validates an email address.z.string().optional()defines an optional string.
- Parsing:
schema.parse(data)parses data against a schema and throws an error if validation fails.schema.safeParse(data)parses data against a schema and returns a success/failure result object similar to Valibot.
- Type Inference: Zod uses
z.infer<typeof schema>to extract the TypeScript type from a schema.
Error Handling and Human-Readable Errors
- Valibot: Uses
V.summarize(issues)to generate human-readable error messages from theissuesarray. - Zod: Uses
prettyError.format(error)to generate human-readable error messages from the error object.
Custom Validators
Both Valibot and Zod allow you to define custom validators to enforce specific data constraints.
- Valibot: Uses
V.custom(validatorFunction, errorMessage)to create a custom validator. ThevalidatorFunctionshould return a boolean indicating whether the data is valid. - Zod: Uses
schema.refine(validatorFunction, errorMessage)to add a custom validation rule to a schema.
Example (Phone Number Validation):
- Valibot:
V.string().optional().pipe(V.custom((value) => { return /^\(\d{3}\) \d{3}-\d{4}$/.test(value); }, 'Invalid phone number format')); - Zod:
z.string().optional().refine((value) => { if (!value) return true; // Allow optional to pass through return /^\(\d{3}\) \d{3}-\d{4}$/.test(value); }, 'Invalid phone number format');
Data Transformation
Both libraries allow you to transform data during the parsing process.
- Valibot: Uses
V.transform(transformFunction)to apply a transformation to the data. - Zod: Uses
schema.transform(transformFunction)to apply a transformation to the data.
Example (Uppercasing a String):
- Valibot:
V.string().pipe(V.transform((value) => value.toUpperCase())); - Zod:
z.string().transform((value) => value.toUpperCase());
JSON Schema Generation
Both Valibot and Zod can generate JSON schemas from their schemas, which is useful for AI applications and other scenarios where a standardized data description is needed.
- Valibot: Uses the
valibot-to-json-schemalibrary.toJsonSchema(schema)converts a Valibot schema to a JSON schema.
- Zod: Has built-in JSON schema generation.
schema.toJsonSchema()converts a Zod schema to a JSON schema.
Adding Descriptions for LLMs:
To make JSON schemas more useful for Large Language Models (LLMs), you can add descriptions to the schema properties.
- Valibot: Add metadata to the schema using
V.metadata({ description: '...' }). - Zod: Chain the
.describe('...')method to the schema property.
Zod Mini
Zod Mini is a smaller, more tree-shakeable version of Zod that uses a functional chaining approach similar to Valibot. It aims to reduce bundle size.
- Import: Import from
zod/miniinstead ofzod. - Schema Definition: Uses a
checkmethod similar to Valibot'spipefor combining validations.
Conclusion
Valibot and Zod are powerful tools for runtime type checking in JavaScript and TypeScript. They offer different approaches to schema definition and parsing, but both provide features like custom validators, data transformation, and JSON schema generation. Zod Mini offers a smaller bundle size with a functional chaining approach. The choice between Valibot and Zod depends on personal preference and project requirements.
AI summaries can miss context or contain errors. Check important details against the original video.





