Types You Don't Control 12 exercises
explainer

Types that Ship With Libraries

Zod is a fantastic data validation library that enables us to construct and validate data objects at runtime. You don't have to install separate types for Zod, because it comes bundled with its own.

Once you install Zod, the types will be available right away:


pnpm i zod

After install

Loading explainer

Transcript

00:00 We've talked about the situation where you don't have types for your library, but what about the situation where you do? Well, we're using Zod here, and Zod is a really amazing library written for data validation, so we can create data objects and validate that everything is working at runtime as we expect.

00:18 I've also got a free tutorial on Zod on Total TypeScript, too. So Zod is great, and another reason Zod is great is because it bundles its own types, meaning that you only ever need to install Zod, not types Zod. This means that when we go into node modules where Zod has been installed, we can see right away there's an index.d.ts file here.

00:37 If we look at package.json here, we can see that there's a reference to it inside types here, which you don't need to do, but it is doing here. And then inside lib, every single JS file here has an accompanying .d.ts file that explains what's going on inside that file. This means that TypeScript can just read these declaration files,

00:56 understand what is being exported from these files, and boom, you're ready to go. This means that when we go back to our code that we actually had just here, we can just kind of import Z from Zod, which is the typical way you import it, and you get beautiful autocomplete, so Z.number, for instance, for age, let's say, and it just works straight out of the box.

01:15 So this is how it works in TypeScript. If you have some declaration files next to some JavaScript files, wherever they are, whether they're in your Node modules, whether they're in your code, TypeScript will understand that that .d.ts file basically corresponds to, if we look back again inside here, corresponds to an accompanying .js file,

01:34 which is just a lovely system, and it means that if you're shipping a library, you need to make sure that you're bearing that in mind, and we'll look at the configuration for that later.