Type Inference
on this page
So far we have only looked at how to validate our data, but we have not fully taken advantage of what Zod has to offer, and what sets it apart from other data validation libraries.
Automatic type inference
Zod lets you infer the type of an object from the schema. Lets use the schema we defined earlier.
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))
});
Assume you are fetching a blog post from an endpoint, and storing it in a variable.
const response = await fetch("....");
const post = await response.json();
Now we can go ahead and validate this post using our postSchema.
postSchema.parse(post)
Lets assume that the validation passes. There is still one problem. The type of the post variable will be any because that is the return type of fetch. This means that we could access attributes that do not exist, and typescript cannot help us. This is where Zod shines. The parse method also returns a correctly type version of the post.
const typedPost = postSchema.parse(post)
Now we will get intelligent typing, and auto complete on the typedPost variable.
Infer type helper
If we need to infer the type of a schema manually, Zod provides an infer type helper. We can use it to extract the type of the object schema.
type Post = z.infer<typeof postSchema>;
function SubmitPost(post : Post) {
/*implementation here*/
}
Im sure you can already realize how useful, and powerful this is. Zod greatly enhances the developer experience by eliminating duplicating of code, and providing a single source of types, along with runtime data validation.