All Tutorials

Zod

Zod

TypeScript is great for checking variables at the type level.

For example, you can specify that the age property for a User should be a number.

However, you can’t always be sure what you’re going to get from a form input. TypeScript will present an error if it’s not a number, but on its own it doesn’t know if a number is too low or too high to be realistic for your use case.

There’s a similar problem with third-party API responses.

You can reference documentation to get an idea for what a response includes, but TypeScript can’t tell how to type it. And what happens if you get an error instead?

Zod allows you to work around uncertainty by checking types at the runtime level as well at the type level.

In this tutorial, you’ll gain hands-on practice with Zod by working through a series of exercises that demonstrate how useful runtime checking is.

What is Zod?

Zod (github) is a TypeScript-first schema declaration and validation library. I'm using the term "schema" to broadly refer to any data type, from a simple string to a complex nested object.

Zod is designed to be as developer-friendly as possible. The goal is to eliminate duplicative type declarations. With Zod, you declare a validator once and Zod will automatically infer the static TypeScript type. It's easy to compose simpler types into complex data structures.

Instructions

This tutorial is a set of problem exercises for you to work through. Each exercise has a short video that presents the problem along with a code editor to solve the problem in the browser.

You'll know you've solved the exercise when the tests pass.

This Zod tutorial encourages active, exploratory learning. In each exercise, I'll explain a problem, and you'll be asked to try to find a solution.

To attempt a solution, you'll need to:

  1. Look for any 🕵️‍♂️ emojis to give you a hint on what to change
  2. Check out Zod's docs
  3. Try to find something that looks relevant.
  4. Give it a go to see if it solves the problem.

You'll know if you've succeeded because the tests will pass.

If you succeed, or if you get stuck, watch the solution video and check out the *.solution.ts.

You can see if your solution is better or worse than mine!

Prerequisites

You'll need a working understanding of JavaScript, but even if you are new to TypeScript this tutorial is for you.

Running the Exercises Locally

You'll want to have an understanding of git to clone the repository, basic node and npm (yarn) , as well as TypeScript itself to work through this tutorial.

If you want to save your work or work in a different environment, you can also clone the git repository and work locally in the editor of your choice. If you follow this link to use gitpod, you can work in a full VS Code coding environment running in your browser.

Follow the instructions in the README to get the exercises running.

Contents

10 Lessons