External Libraries 9 exercises

Browsing Zod's Types

In the next exercise we'll be working with the Zod library, but first here's a brief overview of its types.

Consider this code:

import { z } from "zod";
type Example = z.ZodType;

ZodType is an abstract class that forms the basis of Zod's generic structure.

Many things in Zod

Loading explainer


0:00 In the exercise after this, we're going to look at Zod and Zod's types. We're going to start looking at the generics flow inside Zod. I want to take you through a brief little tour of what Zod really looks like. ZodType especially, is what I want you to look at.

0:16 ZodType is an abstract class that sits at the bottom of Zod's, basically, their generic structure. Everything in Zod essentially extends ZodType. You can see there's, whoo, 152. Although a lot of these are extending different things.

0:33 ZodType, 38 different things look like they extend ZodType and pass things to it. For instance, ZodVoid extends ZodType void VoidDef. ZodNever extends ZodType never ZodNeverDef. Everything in Zod, everything that you can return from like example, z.string, z.number, for instance.

0:58 Z.string will return z.ZodString. Let's take a look at that. Gets a ZodString which extends ZodType string. Zod.void extends ZodVoid which extends ZodType void ZodVoidDef.

1:14 Your goal here basically, in the next exercise, I'm going to be asking you to take a look at Zod structure and understand its flow of generics. The three main ones you need to pay attention to are output, which is going to equal any by default.

1:30 Def extends ZodTypeDef equals ZodTypeDef. This one is an internal one that tracks various things to do with the way you declare object schemas and things like this. Finally, input.

1:45 The way Zod works is you can actually have a different type on the input than you have on the output. For instance, if you have const transformer, we have Z.string, and then we can transform that string into a, let's say we go, transform it into a number. Number s.

2:06 Now what you'll see is we have z.ZodEffects, z.ZodString, number, string. Let's have a look at that. We have z.ZodEffects, ZodEffects, Zod extends ZodType, and then we have input and output here. This is cool.

2:26 What this means is you can see that actually this is funky because the order gets a bit shifted around here. ZodEffects, z.ZodString, number, string still extends ZodType. We can still do transformer pass and things.

2:39 You want to pay attention to the input and output types in the next exercise. Good luck.