DEV Community

Renato Sinohara
Renato Sinohara

Posted on

Create a self verifying type library with Zod

If you use Typescript, you probably wished it could do 2 more tings:

  • Verify at run time if a type matches your schema
  • Make sure no unexpected fields exist in objects.

Zod

Zod (github) allows you to do exactly that.

import { z } from "zod";

// creating a schema for strings
const foodNameSchema = z.string();
foodNameSchema.parse("tuna"); // => "tuna"
foodNameSchema.parse(12); // => throws ZodError
Enter fullscreen mode Exit fullscreen mode

Zod can be used to create Typescript types, so we also have all the compile time goodness.

export type FoodName = z.infer<typeof foodNameSchema>;
Enter fullscreen mode Exit fullscreen mode

Now, some might say parsing will add performance impact. This might matter to you.
But in this article, we show a different usage that dodges that completely.

Self verifying type library

Chances are you have an internal library to share your common types. Especially if you are or intend to use micro frontends.

What we have been doing in my team is to use Zod's parsing to make sure this type library is always up to date with our live formats.

By ensuring all production types match our schemas exactly, we can rely on our types 100%. Call it contract testing, but we also use the same schemas in our code.

This also has no runtime impact. In fact, our other projects need not even import Zod.

Usage

Any typescript project can import the types or Zod schemas at will. Pure JS projects can also use Zod schemas, if desired.
Zod can be exported to JSON schema, so other languages could also benefit.

During deployment, the type library crawls and checks the types of API and CSR initial props, making sure the schemas are all correct.

Top comments (0)