A crash course on Zod - a schema validation library for TypeScript

Overview

Zod Crash Course

This Zod crash course will give you everything you ever needed to know about Zod - an amazing library for building type-safe AND runtime-safe applications.

Quickstart

# Installs all dependencies
yarn install

# Starts the first exercise
yarn exercise 01

# Runs linting and tests on the solution
yarn solution 01

How to take the course

First, start up the video on YouTube.

You'll notice that the course is split into exercises. Each exercise is split into a *.problem.ts and a *.solution.ts.

To take an exercise:

  1. Go into *.problem.ts
  2. Run yarn exercise 01, where 01 is the number of the exercise you're on.

The exercise script will run TypeScript typechecks and a test suite on the exercise.

This course encourages active, exploratory learning. In the video, 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, unpause the video and check out the *.solution.ts. You can see if your solution is better or worse than mine!

You can run yarn solution 01 to run the tests and typechecking on the solution.

Acknowledgements

Say thanks to Matt on Twitter or by joining his Discord. Consider signing up to his Total TypeScript course.

Reference

yarn exercise 01

Alias: yarn e 01

Run the corresponding *.problem.ts file.

yarn solution 01

Alias: yarn s 01

Run the corresponding *.solution.ts file. If there are multiple, it runs only the first one.

Comments
  • Screen flickers on 1920 × 980px screen

    Screen flickers on 1920 × 980px screen

    Page : https://www.totaltypescript.com/tutorials/zod/optional/solution

    some weird behavior on this page only, the screen flickers continuously on my large-resolution monitor but works fine for monitor with small resolution. Screen Size: 1920px × 1080px

    I've attached video but unfortunately, my screen recorder couldn't capture the fps on which the screen is flickering.

    https://user-images.githubusercontent.com/50266088/194393200-d6953aa6-e481-453e-af03-7a4f313c5f3e.mp4

    opened by adarshaacharya 2
  • fix: typo in the exercise title

    fix: typo in the exercise title

    Hi there,

    Thank you very much for such great tutorials. One small thing - there is a typo I think on the tutorial environment. Not sure where to mention it, maybe in this repo.

    I guess it should be "Extract a type from a Parser Object"

    image

    Apologies if that's not the right place to mention this kind of things. Thanks again for the amazing tutorial!

    opened by AlixFachin 1
  • Suggest : add problem 15 for zod record

    Suggest : add problem 15 for zod record

    thanks for helpful tutorial :) i had never know zod before i know this tutorial. i think adding problem about zod's record is very helpful.

    how do you think about my suggestion?

    if you like i will add new problem for zod record

    opened by alajillo 1
  • ✨ FR: Add a z.refine() example

    ✨ FR: Add a z.refine() example

    I often happens in form validation that you have to compare two date fields, like from -> to, that is also possible in zod with refine as far as I remember.

    opened by hinogi 1
  • Remove reference to video in README.md

    Remove reference to video in README.md

    The previous PR removed the mention of the YouTube video (which was included as a TODO previously). This further cleans up the README by removing the other reference to using a video.

    I'm not sure whether the video is still planned to be included, but until it is it might be best to avoid confusion!

    opened by themagickoala 0
  • Exercise script always run all tests

    Exercise script always run all tests

    I'm using

    • Windows 11
    • Node v16.15.1

    When executed the exercise script, e.g. yarn exercise 01, it runs tests for all problems instead of the particular problem image

    opened by AriGunawan 0
  • fix: typo in exercise 08 problem description

    fix: typo in exercise 08 problem description

    Hi, Matt!

    Really enjoying the tutorial and carefully reading every sentence 🤓

    Should this read "... to pass any invalid email, phone number, or website url."? I reckon it should, since you speak about them in the video, but the inputs are singular.

    Screenshot 2022-11-26 at 22 26 03

    Keep on the great work! Cheers

    opened by seblondono 0
  • feat(07): add third solution to exercise 07 using 'or' function

    feat(07): add third solution to exercise 07 using 'or' function

    PR Type

    What kind of change does this PR introduce?

    [ ] Bugfix
    [x] Feature
    [ ] Code style update (formatting, local variables)
    [ ] Refactoring (no functional changes, no api changes)
    [ ] Build related changes
    [ ] CI related changes
    [ ] Documentation content changes
    [ ] Other... Please describe:
    

    What is the current behavior?

    Exercise 07 solutions don't contain the "or" usage alternative

    Fixes: #4

    What is the new behavior?

    Exercise 07 has a third solution using the "or" function from Zod

    opened by NachoVazquez 0
  • feat: add

    feat: add "or" solution to "07 union problem"


    name: Feature request about: Suggest an idea for this project title: 'add "or" solution to "07 union problem"'

    What is the motivation/use case for changing the behavior?

    When discussing the possible solutions for exercise 07, it would be nice to include the use of "or" as a union alternative.

    Describe the solution you'd like

    Add the following as a third solution.

    const Form = z.object({
      repoName: z.string(),
      privacyLevel: z.literal('private').or(z.literal('public')),
    });
    
    opened by NachoVazquez 0
  • Exercise 14: incorrect return type passes

    Exercise 14: incorrect return type passes

    Currently both of these "solutions" pass exercise 14:

    // correct
    const genericFetch = <Schema extends z.ZodSchema>(
      url: string,
      schema: Schema
    ): Promise<z.infer<Schema>> => {
      return fetch(url)
        .then((res) => res.json())
        .then((result) => schema.parse(result));
    };
    
    // incorrect, doesn't return a promise
    const genericFetch = <Schema extends z.ZodSchema>(
      url: string,
      schema: Schema
    ): z.infer<Schema> => {
      return fetch(url)
        .then((res) => res.json())
        .then((result) => schema.parse(result));
    };
    

    This is because the current test case checks the type of result, which awaits genericFetch, so it doesn't care if genericFetch returns a Promise or not.

    I came up with two possibilities for a test case that catches this - I don't love either of these, maybe a TS Wizard could come up with something more elegant.

    1. Just check that genericFetch returns a promise of some sort
    Expect<Equal<ReturnType<typeof genericFetch>, Promise<z.TypeOf<any>>>>
    
    1. Check the entire type of genericFetch
    Expect<
      Equal<
        typeof genericFetch,
        <Schema extends z.ZodType<any, z.ZodTypeDef, any>>(
          url: string,
          schema: Schema
        ) => Promise<z.TypeOf<Schema>>
      >
    >
    
    opened by c-ehrlich 0
GatsbyConf - Decoupling Drupal Using Gatsby: A Crash Course workshop

GatsbyConf - Decoupling Drupal Using Gatsby: A Crash Course workshop

Octahedroid 7 Sep 29, 2022
Generate a zodios (typescript http client with zod validation) from an OpenAPI spec (json/yaml)

openapi-zod-client Generates a zodios (typescript http client with zod validation) from a (json/yaml) OpenAPI spec (or just use the generated schemas/

Alexandre Stahmer 104 Jan 4, 2023
Prisma 2+ generator to emit Zod schemas from your Prisma schema

Prisma Zod Generator Automatically generate Zod schemas from your Prisma Schema, and use them to validate your API endpoints or any other use you have

Omar Dulaimi 212 Dec 27, 2022
Wrap zod validation errors in user-friendly readable messages

zod-validation-error Wrap zod validation errors in user-friendly readable messages. Features User-friendly readable messages, configurable via options

Causaly 70 Dec 23, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
validation-first schema library with a functional api

zap ⚡ zap is a validation-first schema library with a functional Api. Some major features are Flexible refinement and validation API Transformation, C

Spaceteams GmbH 19 Dec 5, 2022
A simple CLI to generate a starter schema for keystone-6 from a pre-existing prisma schema.

Prisma2Keystone A tool for converting prisma schema to keystone schema typescript This is a proof of concept. More work is needed Usage npx prisma2key

Brook Mezgebu 17 Dec 17, 2022
Three JS Crash kursi 2022 (Amaliyot asosida)

Video kurs: https://www.youtube.com/watch?v=NL2Cv8N1Skg Kursdagi presentatsiya: https://bit.ly/3aRRf9M Loyiha demosi: https://harmonious-puppy-4ea920.

Javohir Hakimov 5 Oct 28, 2022
Bloxflip crash automation using the martingale strategy. Earn robux passively while you sit back!

bloxflip-autocrash Bloxflip crash automation using the martingale strategy. Earn robux passively while you sit back! ⚠️ WARNING This automation softwa

null 17 Dec 30, 2022
Full-stack-todo-rust-course - we are building this out now in prep for the real course

full-stack-todo-rust-course wip - we are building this out now in prep for the real course Plan Come up with the requirements Create user stories Desi

Brooks Builds 89 Jan 2, 2023
We are students of group named "Special-Team" of GоIT academy. We graduated JavaScript course and for consolidate in practice 📌 knowledges received on this course, we together 🤝 developed graduation project

Проект сайту "Filmoteka" Привіт! ?? Ми студенти групи під назвою "Special-Team" академії GоIT ?? ?? Ми закінчили курс JavaScript і для того, щоб закрі

Oksana Banshchykova 12 Jan 3, 2023
Course material for a ~10 hours introductionary course for Julia. Topics: Introduction, Parallel Programming, Data Science

Development We use Franklin.jl to generate the lecture material. To do so, simply activate the environment, use Franklin and run the local server: act

GregorE 3 Dec 15, 2022
RenderIf is a function that receives a validation as a parameter, and if that validation is true, the content passed as children will be displayed. Try it!

RenderIf RenderIf is a function that receives a validation as a parameter, and if that validation is true, the content passed as children will be disp

Oscar Cornejo Aguila 6 Jul 12, 2022
Zod utilities for Remix loaders and actions.

Zodix Zodix is a collection of Zod utilities for Remix loaders and actions. It abstracts the complexity of parsing and validating FormData and URLSear

Riley Tomasek 172 Dec 22, 2022
typescript-to-jsonschema generates JSON Schema files from your Typescript sources.

fast-typescript-to-jsonschema English | 简体中文 a tool generate json schema from typescript. Feature compile Typescript to get all type information conve

yunfly 21 Nov 28, 2022
Mike North's "Making TypeScript Stick" course.

Mike North's "Making TypeScript Stick" course.

Mike North 24 Oct 30, 2022
Mike North's full-stack TypeScript Course

Full Stack TypeScript Mike North's Full Stack TypeScript course Video: Frontend Masters Course website: TypeScript Training: Full Stack TypeScript Set

Mike North 50 Dec 21, 2022