Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 12, 2021 07:35 am GMT

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 stringsconst foodNameSchema = z.string();foodNameSchema.parse("tuna"); // => "tuna"foodNameSchema.parse(12); // => throws ZodError

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

export type FoodName = z.infer<typeof foodNameSchema>;

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.


Original Link: https://dev.to/rsinohara/create-a-self-verifying-type-library-with-zod-2l74

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To