Learning Zod, not a technical sharing
What is Zod
Zod is a library that helps TypeScript users with type inference and validation during both writing and runtime. It greatly maintains TypeScript type safety, has zero external dependencies, is lightweight, and is very popular.
Simple usage of Zod
Below is the usage of Zod seen in NuxtContent. I saw Zod while reading the documentation today, realized I didn't know how to use it, so I learned it.
// code
schema: z.object({
// Hero area: CTA button group + carousel image group
hero: z.object({
links: z.array(createButtonSchema()),
images: z.array(createImageSchema())
}),The usage of Zod is very simple, so simple that by translating the above code for you, you will understand how to use it.
- schema must be an object type and must have a hero property below
- hero property must be an object and must have links and images properties
- links must be an array, and the element type in the array must be the return type of the createButtonSchema() method, or pass the validation of this return value (the method name suffix Schema actually implies that the return value of this method is also an object constrained by z.object)
- images is similar to links Right? It's easy to understand at a glance, and also easy to use (probably?). Then you can use parse() to validate your data, like this: schema.parse(data). If the parse validation fails at runtime, it will directly throw an error, while TypeScript only throws an error when you use such an incorrect data type (for example, using the toFixed method on a String type). This also shows that it is safer than TypeScript, focusing on runtime data safety.
If you don't want it to throw an error at runtime, you can use safeParse (using this API often means you expect the data to be correct). The method returns an object:
If the data is correct, it returns an object like this:
In frontend development with TypeScript, if you want to validate form data, you no longer need to first define an interface and then write validation logic. You can directly use Zod to define a schema, then use parse to validate, or use type register = z.infer to directly generate an interface, along with validation rules.
Summary
The emergence of Zod adds a layer of safety to TypeScript code at runtime, simplifies some basic validation rules, and more features can be explored when needed.
Comments
No comments yet. Say something?