Transformation

Zod is a powerful library that offers a variety of features for working with schemas. One of its standout features is the transform method, which allows you to manipulate data within schemas. In this guide, we'll explore how to use this feature effectively.

Example Schema: Blog Post Data

Let's start with an example. Imagine you have data for a blog post stored in a local JSON file. You've defined a schema called postSchema to validate this data, including a publishedDate field that should follow the format YYYY-MM-DD.

const postSchema = z.object({
	postId : z.number(),
	title : z.string().min(1),
	body : z.string().min(1),
	authorName : z.string().min(1),
	tags : z.array(z.string().min(1)),
	publishedDate : z.string().regex(/*some regex to validate date*/)
});

Notice that we've applied a regex method to validate the date format.

Validating Data with Zod

Now we can go ahead and validate our post against this schema.

const post = postScema.parse({/* post data */})

Manual Transformation

Lets say we want to convert the publishedDate to a Date object type. This can be done manually but its not very idiomatic.

const postWithDate = {...post, publishedDate : new Date(post.publishedDate)}

Zod Transformation

Zod understands that manual transformations can be cumbersome. Therefore, it provides a more declarative approach using transformations. Here's how you can apply one to the publishedDate field:

const postSchema = z.object({
	postId : z.number(),
	title : z.string().min(1),
	body : z.string().min(1),
	authorName : z.string().min(1),
	tags : z.array(z.string().min(1)),
	publishedDate : z.string().regex(/*...*/).transform(val => new Date(val))
});

This transformation function will not only transform the string to a Date object at run-time, but it will also transform its type. Now the inferred type of publishedDate will be Date instead of string.

The parse method, and infer type helper will accurately infer the transformed type.

This declarative approach simplifies your code and makes it more expressive when dealing with schema transformations in Zod.