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.

8 min
06 Jun, 2023

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.

Available in Español

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

React Advanced Conference 2021React Advanced Conference 2021
39 min
Don't Solve Problems, Eliminate Them
Top Content
Humans are natural problem solvers and we're good enough at it that we've survived over the centuries and become the dominant species of the planet. Because we're so good at it, we sometimes become problem seekers too–looking for problems we can solve. Those who most successfully accomplish their goals are the problem eliminators. Let's talk about the distinction between solving and eliminating problems with examples from inside and outside the coding world.
Remix Conf Europe 2022Remix Conf Europe 2022
23 min
Scaling Up with Remix and Micro Frontends
Top Content
Do you have a large product built by many teams? Are you struggling to release often? Did your frontend turn into a massive unmaintainable monolith? If, like me, you’ve answered yes to any of those questions, this talk is for you! I’ll show you exactly how you can build a micro frontend architecture with Remix to solve those challenges.
React Advanced Conference 2022React Advanced Conference 2022
30 min
Using useEffect Effectively
Top Content
Can useEffect affect your codebase negatively? From fetching data to fighting with imperative APIs, side effects are one of the biggest sources of frustration in web app development. And let’s be honest, putting everything in useEffect hooks doesn’t help much. In this talk, we'll demystify the useEffect hook and get a better understanding of when (and when not) to use it, as well as discover how declarative effects can make effect management more maintainable in even the most complex React apps.
React Advanced Conference 2021React Advanced Conference 2021
47 min
Design Systems: Walking the Line Between Flexibility and Consistency
Top Content
Design systems aim to bring consistency to a brand's design and make the UI development productive. Component libraries with well-thought API can make this a breeze. But, sometimes an API choice can accidentally overstep and slow the team down! There's a balance there... somewhere. Let's explore some of the problems and possible creative solutions.
React Summit 2023React Summit 2023
23 min
React Concurrency, Explained
Top Content
React 18! Concurrent features! You might’ve already tried the new APIs like useTransition, or you might’ve just heard of them. But do you know how React 18 achieves the performance wins it brings with itself? In this talk, let’s peek under the hood of React 18’s performance features: - How React 18 lowers the time your page stays frozen (aka TBT) - What exactly happens in the main thread when you run useTransition() - What’s the catch with the improvements (there’s no free cake!), and why Vue.js and Preact straight refused to ship anything similar
Remix Conf Europe 2022Remix Conf Europe 2022
37 min
Full Stack Components
Top Content
Remix is a web framework that gives you the simple mental model of a Multi-Page App (MPA) but the power and capabilities of a Single-Page App (SPA). One of the big challenges of SPAs is network management resulting in a great deal of indirection and buggy code. This is especially noticeable in application state which Remix completely eliminates, but it's also an issue in individual components that communicate with a single-purpose backend endpoint (like a combobox search for example).
In this talk, Kent will demonstrate how Remix enables you to build complex UI components that are connected to a backend in the simplest and most powerful way you've ever seen. Leaving you time to chill with your family or whatever else you do for fun.

Workshops on related topic

React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Top Content
Featured WorkshopFree
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 Summit Remote Edition 2021React Summit Remote Edition 2021
177 min
React Hooks Tips Only the Pros Know
Top Content
Featured Workshop
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 Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Top Content
Featured WorkshopFree
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.
React Advanced Conference 2021React Advanced Conference 2021
145 min
Web3 Workshop - Building Your First Dapp
Top Content
Featured WorkshopFree
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.
React Summit 2023React Summit 2023
151 min
Designing Effective Tests With React Testing Library
Top Content
Featured Workshop
React Testing Library is a great framework for React component tests because there are a lot of questions it answers for you, so you don’t need to worry about those questions. But that doesn’t mean testing is easy. There are still a lot of questions you have to figure out for yourself: How many component tests should you write vs end-to-end tests or lower-level unit tests? How can you test a certain line of code that is tricky to test? And what in the world are you supposed to do about that persistent act() warning?
In this three-hour workshop we’ll introduce React Testing Library along with a mental model for how to think about designing your component tests. This mental model will help you see how to test each bit of logic, whether or not to mock dependencies, and will help improve the design of your components. You’ll walk away with the tools, techniques, and principles you need to implement low-cost, high-value component tests.
Table of contents- The different kinds of React application tests, and where component tests fit in- A mental model for thinking about the inputs and outputs of the components you test- Options for selecting DOM elements to verify and interact with them- The value of mocks and why they shouldn’t be avoided- The challenges with asynchrony in RTL tests and how to handle them
Prerequisites- Familiarity with building applications with React- Basic experience writing automated tests with Jest or another unit testing framework- You do not need any experience with React Testing Library- Machine setup: Node LTS, Yarn
React Summit 2022React Summit 2022
136 min
Remix Fundamentals
Top Content
Featured WorkshopFree
Building modern web applications is riddled with complexity And that's only if you bother to deal with the problems
Tired of wiring up onSubmit to backend APIs and making sure your client-side cache stays up-to-date? Wouldn't it be cool to be able to use the global nature of CSS to your benefit, rather than find tools or conventions to avoid or work around it? And how would you like nested layouts with intelligent and performance optimized data management that just works™?
Remix solves some of these problems, and completely eliminates the rest. You don't even have to think about server cache management or global CSS namespace clashes. It's not that Remix has APIs to avoid these problems, they simply don't exist when you're using Remix. Oh, and you don't need that huge complex graphql client when you're using Remix. They've got you covered. Ready to build faster apps faster?
At the end of this workshop, you'll know how to:- Create Remix Routes- Style Remix applications- Load data in Remix loaders- Mutate data with forms and actions