8 Ways that I use Zod to Improve the Quality of My Code

post-title

Zod is a TypeScript-first schema declaration and validation library for JavaScript. It is designed to be as developer friendly as possible, with the goal of eliminating duplicative type declarations. If you are looking for a trustworthy schema validation library in JavaScript, Zod is the one for you. With Zod, you declare a validator once and Zod will automatically infer the static TypeScript type. It is also easy to compose simpler types into complex data structures. In this blog post, we will explore different ways to use Zod to improve the quality of your code.

Using Zod to validate your data can help you to improve the quality of your code in a number of ways:

  • It can help to prevent errors by catching type mismatches and other data validation errors.
  • It can make your code more readable and maintainable by documenting the structure of your data.
  • It can improve the performance of your code by caching frequently used validation rules.
  • It can make your code more reliable by providing a consistent way to handle validation errors.

_

1. Type/Schema Definition

Zod is primarily used for defining and working with schemas or types in JavaScript. It allows you to create structured schemas that enforce type safety.

const { z } = require("zod");

const userSchema = z.object({
  id: z.number(),
  name: z.string(),
  email: z.string().email(),
});

const user = userSchema.parse({
  id: 1,
  name: "John Doe",
  email: "[email protected]",
});

2. Inferring the type of a schema

Zod is capable of inferring the type from a defined schema. This is useful for improving code clarity and avoiding repetitive type declarations.

const { z } = require("zod");

const userSchema = z.object({
  id: z.number(),
  name: z.string(),
  email: z.string().email(),
});

type User = z.infer<typeof userSchema>;

const user: User = {
  id: 1,
  name: "John Doe",
  email: "[email protected]",
};

3. Form/Data Validation

Zod can be used for validating form data on the client side, ensuring that the data conforms to a predefined schema.

const { z } = require("zod");

const formData = {
  username: "JohnDoe",
  password: "pass123",
};

const formSchema = z.object({
  username: z.string().min(4),
  password: z.string().min(6),
});

try {
  formSchema.parse(formData);
  // Data is valid
} catch (error) {
  // Handle validation error
  console.error(error.message);
}

4. API Response Validation

You can use Zod to validate data received from APIs, ensuring it matches the expected schema.

const { z } = require("zod");

const response = {
  status: "success",
  data: {
    id: 1,
    name: "John Doe",
  },
};

const responseSchema = z.object({
  status: z.literal("success"),
  data: z.object({
    id: z.number(),
    name: z.string(),
  }),
});

try {
  responseSchema.parse(response);
  // API response is valid
} catch (error) {
  // Handle validation error
  console.error(error.message);
}

5. Enum Validation

Zod allows you to define enums and validate that a value matches one of the enum options.

const { z } = require("zod");

const genderEnum = z.enum(["Male", "Female", "Other"]);

const user = {
  name: "Alice",
  gender: "Female",
};

try {
  genderEnum.parse(user.gender);
  // Gender is valid
} catch (error) {
  // Handle validation error
  console.error(error.message);
}

6. Partial

Zod's z.partial is useful when you want to validate an object with optional properties.

const { z } = require("zod");

const userSchema = z.object({
  id: z.number(),
  name: z.string(),
  email: z.string().email(),
});

const partialUser = z.partial(userSchema);

const user = partialUser.parse({
  name: "John Doe",
  email: "[email protected]",
});

7. Pick and Omit

Zod provides z.pick and z.omit to create new schemas by selecting or excluding specific properties from an existing schema.

const { z } = require("zod");

const userSchema = z.object({
  id: z.number(),
  name: z.string(),
  email: z.string().email(),
  age: z.number(),
});

const userWithIdAndEmail = z.pick(userSchema, ["id", "email"]);

const userWithoutAge = z.omit(userSchema, ["age"]);

8. Extend

With z.extend, you can add new properties to an existing schema while keeping the existing properties.


const { z } = require("zod");


const userSchema = z.object({
  id: z.number(),
  name: z.string(),
});

const extendedUserSchema = userSchema.extend({
  email: z.string().email(),
  age: z.number(),
});

These are just some of the use cases of the Zod JavaScript library that I usually used in my projects. You can checkout their repository for more details https://github.com/colinhacks/zod .