Zod === Typescript, but at Runtime in Your React Applications

Rate this content
Bookmark
Slides

In this talk, I want to show how we can use Zod to guarantee the type in a React Application at runtime. Environment variables, HTTP requests, forms and so on could create troubles in our applications, mainly if they contain unexpected types. Using Zod, we can create schemas to guarantee the types expected in our editor at runtime. In this way, we can react quickly when an environment variable misses or when someone changes the API contract without informing us.
A small validation layer in our applications can prevent a bad user experience and notify us immediately, so we can fix the problem as soon as possible and mitigate the visualization of wrong data.

This talk has been presented at React Summit 2023, check out the latest edition of this React Conference.

Watch video on a separate page

FAQ

Luca De Pupo is a Software Engineer at Dreams, a JavaScript and TypeScript enthusiast, a content creator on YouTube, and a blog writer. He also enjoys running, hiking, and animals.

Zod is a simple NPM library that allows you to create custom schemas for JavaScript objects, ensuring type validation at runtime.

TypeScript cannot check types at runtime because the code that runs in the browser is JavaScript, not TypeScript.

Zod allows you to create schemas that define your types. These schemas can be used to validate objects at runtime, ensuring they match the expected types. If they don't, Zod raises an error.

The 'parse' method in Zod is used to check if an object matches the expected schema. If the object does not match, it raises a ZodError containing details about what is wrong.

The benefits of using Zod include creating a validation layer between your application and APIs, preventing the execution of code with incorrect data, showing readable errors, and sending notifications to tools like Datadog or Sentry to fix issues quickly.

Yes, Zod schemas can be converted to TypeScript types using the 'type of' method, allowing you to gain the benefits of TypeScript while ensuring runtime type validation.

If a backend API changes and returns data with incorrect types, Zod will raise an error when the data is validated against the schema, providing detailed information about the issue.

A common use case for Zod in a React application is to create a validation layer between the application and APIs, ensuring that the data received from APIs matches the expected types before being processed.

Zod improves error handling by providing readable errors that specify the exact issue in the data. This helps developers quickly identify and fix problems, ensuring that the application runs smoothly.

Luca Del Puppo
Luca Del Puppo
8 min
06 Jun, 2023

Comments

Sign in or register to post your comment.

Video Summary and Transcription

Today's Talk discusses how Zod, an NPM library, can guarantee the TypeSystem at runtime, providing all the benefits of TypeScript. Zod's parse method allows for checking if objects match the schema, creating a validation layer between applications and APIs. By combining TypeScript with Zod, developers can ensure type safety at both runtime and build time, preventing code execution with incorrect data and improving the user experience.

1. Guaranteeing TypeSystem at Runtime with Zod

Short description:

Today I talk about how you can guarantee your TypeSystem at runtime using Zot. TypeScript is not able to check types at runtime, but Zod, an NPM library, allows you to create a custom schema that remains alive at runtime. Zod helps you get all the benefits of TypeScript and guarantees your type system at runtime. Each schema exposes a method called parse to check if the object is as expected by the schema. Zod can create a validation layer between your application and the API, allowing you to check if the result of the API is as expected during development.

Hi there, I'm Luca De Pupo, and today I talk about how you can guarantee your TypeSystem at runtime using Zot! So, first of all, who I am? I'm Luca De Pupo, I sign on Software Engine at Dreams, JavaScript and TypeScript Lovers, and in my free time I try to keep content in my YouTube channel and also write some blog posts. I love running, hiking and animal.

By the way, I want to start with a history, so today, almost 10 years ago, born TypeScript, and every JavaScript developer in the world probably was happy. We started to create our interfaces, our types and so on. The world was perfect, but a day, a back-end developer decided to change an API and, unfortunately, change a property from String to Number or Number to String and the result in our application is something like this. Not a number, a string, and so on. This is because TypeScript is not able to check the types at runtime because the code that runs in your browser is Javascript. But how can we prevent this mistake? So our superhero is Zod. Zod is a simple NPM library that allows you to create a custom schema. In this case, the schema is a JavaScript object, so the schema rests alive also at runtime. And this schema contains a definition of your type. In this case, as you can notice, the customer schema is an object with four properties, id of type Number, name, email and phone of type String. Then you can also convert this type, this schema, into a TypeScript type, in this case using the type of method. It's pretty simple, you can use the schema and convert it to TypeScript. This helps you to get all the benefits of TypeScript, but also guarantees your type system at runtime.

Last but not least, each schema exposes a method called parse. This method is used to check if the object is like expected by the schema. In this case, if the object parsed to the parse method is like expected. The customer variable is of type Customer and contains the object. Otherwise, the parse raises an error. This error is of type ZodError and contains the issue and error to understand what is wrong. Which are the benefits of using Zod in our application? Typically, when you create an application, you have your react application and some API to get the data. Using Zod you can create a validation layer between your application and the API. At runtime, you can check if the result of the API is like expected during the development and in this case you are able to run the code only if the types respect the expected type in this case. Otherwise, you can erase an error, show an error to the user and send a notification to Datadog or maybe to Sentry to fix the problem as soon as possible.

So now it's time to see a simple demo to understand how we can use Zod and the benefits of using it. So the demo is pretty simple. There is a list of order and each order has a different property in this case. For instance, if I change my back end, in this case I change the amount from number to string and go back to the application and refresh the page. As you can notice, in this case Zod erased an error and Scribd, which is the problem.

2. Implementing Schemas and Conclusion

Short description:

In this section, we saw how to identify and fix issues in the schema. We also explored how to implement schemas using .object and union types. The schema can be converted to types and used to validate API results. TypeScript understands the result of the parse method and ensures type safety. In conclusion, TypeScript, combined with Zod, allows you to guarantee your type system at both runtime and build time. This helps prevent code execution with incorrect data and ensures a better user experience. You can also receive notifications and take action to fix any issues quickly. Thank you for joining this talk!

As you can notice in the issue property, you can see some info about the problem. In this case, in the path, the first element of the list contains a total object that contains an amount property and this amount property is of type string, but Zod expects a number type. As you can notice, you can have a readable error and you can maybe fix the problem quickly if you want.

So, I go back to that, take back and fix the error and now it's time to see how we can implement this kind of stuff. For instance, in this case, I create a bigger file with all the schema is composed by using .object and for instance, the currency contain an amount of type number and the currency is an union type between dollar and euro, for instance, the same is for the order and so on. Then, if you want, you can also convert the schema to types. Pretty simple using the type of method and then you can use the schema to pass the result of the API, for instance.

In this case, using a fetch, we can call the backend. Using the JSON method, we can pass the result and then using the order array schema, we can pass the result of the data and be sure that the data is of type order model and respect our signature of the type, for instance. For instance, if I use const res='', you can see that the result is an array of order and also TypeScript is able to understand that the result of the parse is an array of order model. So if I go back to the browser and refresh again, as you can notice, now everything is okay because the response is perfect like expected.

Now it's time to go to the conclusion. So, conclusion. TypeScript is awesome, but without you can guarantee your dev system also at runtime if you want. Create a validation layer between your application and the outside, help you to prevent the execution of code with wrong data and maybe to prevent you to see to the user's wrong or strange data in the UI. And also you can get a notification from... You can send a notification to Datadog or to Sendit to fix the problem as soon as possible. Last but not least, using Zod, you can guarantee your type system both runtime and build time. And this is perfect, I suppose, also for you. Okay, that's all. Here are, you can find the slide of the talk. Here you can find my contact, they are open. If you want to chat with me, you are welcome. I hope you enjoyed this talk and bye bye.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Don't Solve Problems, Eliminate Them
React Advanced Conference 2021React Advanced Conference 2021
39 min
Don't Solve Problems, Eliminate Them
Top Content
Kent C. Dodds discusses the concept of problem elimination rather than just problem-solving. He introduces the idea of a problem tree and the importance of avoiding creating solutions prematurely. Kent uses examples like Tesla's electric engine and Remix framework to illustrate the benefits of problem elimination. He emphasizes the value of trade-offs and taking the easier path, as well as the need to constantly re-evaluate and change approaches to eliminate problems.
Scaling Up with Remix and Micro Frontends
Remix Conf Europe 2022Remix Conf Europe 2022
23 min
Scaling Up with Remix and Micro Frontends
Top Content
This talk discusses the usage of Microfrontends in Remix and introduces the Tiny Frontend library. Kazoo, a used car buying platform, follows a domain-driven design approach and encountered issues with granular slicing. Tiny Frontend aims to solve the slicing problem and promotes type safety and compatibility of shared dependencies. The speaker demonstrates how Tiny Frontend works with server-side rendering and how Remix can consume and update components without redeploying the app. The talk also explores the usage of micro frontends and the future support for Webpack Module Federation in Remix.
Using useEffect Effectively
React Advanced Conference 2022React Advanced Conference 2022
30 min
Using useEffect Effectively
Top Content
Today's Talk explores the use of the useEffect hook in React development, covering topics such as fetching data, handling race conditions and cleanup, and optimizing performance. It also discusses the correct use of useEffect in React 18, the distinction between Activity Effects and Action Effects, and the potential misuse of useEffect. The Talk highlights the benefits of using useQuery or SWR for data fetching, the problems with using useEffect for initializing global singletons, and the use of state machines for handling effects. The speaker also recommends exploring the beta React docs and using tools like the stately.ai editor for visualizing state machines.
Design Systems: Walking the Line Between Flexibility and Consistency
React Advanced Conference 2021React Advanced Conference 2021
47 min
Design Systems: Walking the Line Between Flexibility and Consistency
Top Content
The Talk discusses the balance between flexibility and consistency in design systems. It explores the API design of the ActionList component and the customization options it offers. The use of component-based APIs and composability is emphasized for flexibility and customization. The Talk also touches on the ActionMenu component and the concept of building for people. The Q&A session covers topics such as component inclusion in design systems, API complexity, and the decision between creating a custom design system or using a component library.
React Concurrency, Explained
React Summit 2023React Summit 2023
23 min
React Concurrency, Explained
Top Content
Watch video: React Concurrency, Explained
React 18's concurrent rendering, specifically the useTransition hook, optimizes app performance by allowing non-urgent updates to be processed without freezing the UI. However, there are drawbacks such as longer processing time for non-urgent updates and increased CPU usage. The useTransition hook works similarly to throttling or bouncing, making it useful for addressing performance issues caused by multiple small components. Libraries like React Query may require the use of alternative APIs to handle urgent and non-urgent updates effectively.
Managing React State: 10 Years of Lessons Learned
React Day Berlin 2023React Day Berlin 2023
16 min
Managing React State: 10 Years of Lessons Learned
Top Content
Watch video: Managing React State: 10 Years of Lessons Learned
This Talk focuses on effective React state management and lessons learned over the past 10 years. Key points include separating related state, utilizing UseReducer for protecting state and updating multiple pieces of state simultaneously, avoiding unnecessary state syncing with useEffect, using abstractions like React Query or SWR for fetching data, simplifying state management with custom hooks, and leveraging refs and third-party libraries for managing state. Additional resources and services are also provided for further learning and support.

Workshops on related topic

React Performance Debugging Masterclass
React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Top Content
Featured WorkshopFree
Ivan Akulov
Ivan Akulov
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
React Hooks Tips Only the Pros Know
React Summit Remote Edition 2021React Summit Remote Edition 2021
177 min
React Hooks Tips Only the Pros Know
Top Content
Featured Workshop
Maurice de Beijer
Maurice de Beijer
The addition of the hooks API to React was quite a major change. Before hooks most components had to be class based. Now, with hooks, these are often much simpler functional components. Hooks can be really simple to use. Almost deceptively simple. Because there are still plenty of ways you can mess up with hooks. And it often turns out there are many ways where you can improve your components a better understanding of how each React hook can be used.You will learn all about the pros and cons of the various hooks. You will learn when to use useState() versus useReducer(). We will look at using useContext() efficiently. You will see when to use useLayoutEffect() and when useEffect() is better.
React, TypeScript, and TDD
React Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Top Content
Featured WorkshopFree
Paul Everitt
Paul Everitt
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
Web3 Workshop - Building Your First Dapp
React Advanced Conference 2021React Advanced Conference 2021
145 min
Web3 Workshop - Building Your First Dapp
Top Content
Featured WorkshopFree
Nader Dabit
Nader Dabit
In this workshop, you'll learn how to build your first full stack dapp on the Ethereum blockchain, reading and writing data to the network, and connecting a front end application to the contract you've deployed. By the end of the workshop, you'll understand how to set up a full stack development environment, run a local node, and interact with any smart contract using React, HardHat, and Ethers.js.
Mastering advanced concepts in TypeScript
React Summit US 2023React Summit US 2023
132 min
Mastering advanced concepts in TypeScript
Top Content
Featured WorkshopFree
Jiri Lojda
Jiri Lojda
TypeScript is not just types and interfaces. Join this workshop to master more advanced features of TypeScript that will make your code bullet-proof. We will cover conditional types and infer notation, template strings and how to map over union types and object/array properties. Each topic will be demonstrated on a sample application that was written with basic types or no types at all and we will together improve the code so you get more familiar with each feature and can bring this new knowledge directly into your projects.
You will learn:- - What are conditional types and infer notation- What are template strings- How to map over union types and object/array properties.
Deep TypeScript Tips & Tricks
Node Congress 2024Node Congress 2024
83 min
Deep TypeScript Tips & Tricks
Top Content
Featured Workshop
Josh Goldberg
Josh Goldberg
TypeScript has a powerful type system with all sorts of fancy features for representing wild and wacky JavaScript states. But the syntax to do so isn't always straightforward, and the error messages aren't always precise in telling you what's wrong. Let's dive into how many of TypeScript's more powerful features really work, what kinds of real-world problems they solve, and how to wrestle the type system into submission so you can write truly excellent TypeScript code.