Video Summary and Transcription
Zotter is a powerful tool for working with TypeScript in React applications, providing a simple schema concept for validation. It allows you to convert Zod schemas into TypeScript types and check if objects match the schema. Zod can be used for validation and contract enforcement, ensuring data consistency and preventing issues. It can also be used in React applications to create a validation layer and prevent code from running with incorrect data. The speaker encourages questions and provides contact information for further discussion.
1. Introduction to Zotter and TypeScript in React
Hello everybody, and welcome to this talk about Zotter and TypeScript in your React application. Almost a year ago, TypeScript was born. We started to create interfaces to map our model. In our project everything was perfect. Until a day, a backend developer decided to change the API. The superhero is Zod. Zod is a simple NPM package that you can install in your React application. It has a simple concept, the schema concept.
Hello everybody, and welcome to this talk about Zotter and TypeScript in your React application. So, I want to start with a story. So, almost a year ago, TypeScript was born. And every developer, JavaScript developer in the world probably was happy. So, we started to create interfaces to map our model. So, we start to use numbers, string, Boolean and so on. Or maybe types, depending on the scenario you can use interface or types. Whatever you prefer, it's not a problem.
And in our project everything was perfect. We had all the types perfect in our code base. And it was a perfect work for us. Until a day, a backend developer decided to change the API. And unfortunately, he or she decided to change the signature of the API. The result in our React application is something like this. Not a number, not a snippet string, or all the kind of strange JavaScript error that you can image in your React application. These are because yes, Tileset is fantastic. I love it. But after the transpilation, you lose all the types and the code becomes JavaScript code, because in your browser, run only JavaScript code and not tileset code. Sometimes developers forget this stuff and they don't realize this until in production, they don't receive this kind of error.
So, how we can solve this problem in our React or JavaScript or Tilescript applications? So, the superhero is Zod. What is Zod, first of all? Zod is a simple NPM package that you can install in your React application, in your project, using your Package Manager. You can use NPM, install, Zod, and everything is ready to use. Zod has a simple concept, the schema concept. The schema is an object, a real JavaScript object in this case, as you can notice, that describes your object. In this case, a customer schema is a Zod schema that describe that the customer is an object with four properties, the ID, with the type of number, the name with the type string, the email with the type string again, and the same for the phone. You can also add different constraints. For instance, the string can accept also a constraint that this is an email, the phone is a phone and so on. Or you can also build if you want your custom type. For instance, you want a specific case to describe, you can do this. But you can also, for instance, create a num, literal type, whatever you want.
2. Using Zod with TypeScript
The syntax of Zod is similar to TypeScript, making it easy to learn. By using the typeof method, you can convert your Zod schema into a TypeScript type. This allows you to work with TypeScript while maintaining the schema definition at runtime.
As you can notice, the syntax is pretty similar to the TypeScript syntax. So it's not difficult to learn Zod in this case. And you can import and use it using the Zed object in this case, that you can import direct from the Zod library.
Then, yes, in this case, in this moment, Zod has a schema. And now, we have to use it. But it's important to remember that this is a const or let, whatever you prefer, but it's a JavaScript schema. So this schema rest alive also in production, also during the execution of your code. Still alive also in production.
Okay, perfect. But I lose the benefit of using TypeScript, you are thinking, probably. No, because using a simple method called typeof, exposed by the third library, you can convert your schema in a TypeScript type. So in this case, using the typeof, we can convert the customer schema in a customer model using a simple line of code, pretty simple. And using this approach, now we have a TypeScript type, so the customer model, and also the customer schema. So, we have the stuff to work in the best way with the TypeScript, but also something that we can use in our code to maintain and keep alive this definition also at runtime.
3. Using the parse method and handling errors
Using the parse method, Zod can check if an object matches the schema you created. If it does, the parse method returns the object with the expected type. However, if a property doesn't match the schema, an exception is raised. It's crucial to catch and handle these errors, especially in production, to quickly identify and resolve any unexpected issues.
How? Using a simple method called parse. Every schema that you create using Thud is an object. This object expose a simple function called parse that accept an object, something, an object, a string, whatever you want, depend on your schema. And this function parse your object. If your object respect the schema that you have create during your development, the parse return the object, and in this case, the customer variable is of type customer model. So the parse return exactly the type that you expected in a task.
What happens if the parse finds a property that doesn't match your scheme? In this case, the parse raise an error through an exception, pretty simple. So if something went wrong, you receive an exception and you have to handle it in some way. The exception is a dot error. In this case, the dot error is a simple exception, except a error, a java script error with two properties, the issues and the error. In this case, you can find info about the problem in the issue and the error, pretty simple. And it's important to catch and handle this error because if you have an error, you have to understand what is not expected during the execution of your code. And if you are in production, you have to react as soon as possible to this problem.
4. Using Zod for Validation and Contract Enforcement
Zod provides a simple validation layer between your React application and external APIs, ensuring that the received data matches the expected schema. This allows you to confidently run the rest of your code, as any unexpected objects will raise errors and can be quickly fixed. Additionally, Zod can help with contract enforcement in libraries like React-Router-DOM, where the types of parameters may not match your expectations. By creating custom schemas with Zod, you can ensure that the parameters meet your requirements and have the correct types.
Okay, now we have all the notion about Zod and it's time to understand where we can use Zod and all this stuff in our application. So the first benefit that I wanna describe today is this. It's normal for an application to get the data from an API or from a socket. So from something external to the application. This layer of your application is probably the best way to create a layer to check if your data that doesn't depend from you is as expected during the development or during the creation of the signature. Okay? So in this case, between your application and the external API in this case, you can create a simple validation layer using, for instance, a simple example, you have an API that receives a list of order. When you receive the response, you can check if the result is like expected during the development mode, or during the development of your feature. So if you expected that the order have an ID, a amount, and the list of product, you want also at production and during the execution, the response contains all these properties. And this is the first benefit of using VOD. So you can create a simple layer between your react application and the external. And every time you receive some data, an object from outside, you can check if they are like expected. And if it's true, you can run the rest of the code with confidence with confidence because every object is like expected in your signature, in your types. As you can raise an error and send a notification to your sentry, for instance, and check as soon as possible what is the problem and fix it as soon as possible because probably there is a customer with the problem in your application, with your application in this case. Okay, and this is the first benefit.
But Zod can help you also with some contractor exposed by some library that you usually use in your application. For instance, how many of you use the UseParamHook exposed by React-RouterDAO? Okay, this hook is fantastic. But, for instance, in this case, if you ask for the ID, the ID, the type of ID is string or undefined. And the same is for every every params that you decide to put in the UseParam. And maybe you are sure that the ID is a number, for instance. And if you are in this page, the ID is a number and it's not undefined because the router go inside of this route only if the ID is defined. To fix this problem, you can use, for instance, Zot. For instance, you can create your custom UseParams type shape. In this case, you can define the schema for your params. In this case, OrderParamsSchema is a simple object that describes that the params contains an ID. Using the Course and Number method, check if the ID exists and if it is a string. For instance, convert this string in a number. And then in your React component, you can use the UseParam type shape with the schema. And the result is that you have an ID, and the type of this ID, in this case, is a number, as expected. This is the implementation. Using the generics, you can use the schema, and you can pass the schema, and the output and the definition and the input of the type.
5. Using Zod in React Application
Then you pass the schema as parameter and the return is the Z.INF of the schema. This is only one of the use cases. I'm not a fan of prop types. You can use this with.validation in this simple way. If you run this check every time you run the component, your code will start to check the object. This is the last scenario where you can use Zod in your React application. The TypeScript is awesome, but with Zod, it's a bit more. Create a validation layer between your application and the outset is the best way to prevent that your code run with the wrong data.
Then you pass the schema as parameter, and the return is the Z.INF of the schema, so the type of the schema. And the line nine and 10 is the really code that run at the runtime. So useParam, get all the UseParam, and using the schema.pass, you can pass the result. Okay. This is only one of the use cases.
Who loves prop types? I'm not a fan of prop types. So I create a with.validation. This is an iOrder component that accepts a schema and a component. Using this pretty not simple syntax, you can pass the schema and then also a React component and build a function that when you receive a prop, you can check if the props are like expected in your schema and if it's true, you can rent your component as you can raise an error in this case. You can use this with.validation in this simple way, so you can define the props in the schema and then when you export the component, you can use the with.validation, you can pass the schema and then you can pass your component. So you have built a React component check every time if the props of the component respect the schema that you have in mind.
Yes, everything is cool, everything works, but there is a trade-off obviously. If you run this check every time you run the component, your code will start to check the object. You have to understand where you want to put this control. Typically, in my project, I love to put this control in all the components that receive data or that are used from an external application. Maybe, I don't know, you are building a small component that must be included in another application. It's important, in this case, to create this layer because in this way, you can check if your component run as expected, with the right data, or if the problem is because someone called your React component in a wrong way.
That's it. This is the last scenario where you can use Zod in your React application. Yes, there are not only these three examples, but you can imagine your project. If you need something that validates your data, this is the perfect library for you probably. Simple conclusion. This is my personal conclusion. Our personal yet, but I hope you agree with me. The TypeScript is awesome, but with the Zod, it's a bit more. It's a bit more because I love TypeScript, but be sure that also the code during the execution run with the data expected is perfect for me, because I'm sure that all the assumptions are okay also at run time. Create a validation layer between your application and the outset is the best way to prevent that your code run with the wrong data. If you have a problem, you can send a notification to your Sentry and react to this problem as soon as possible. You can guarantee your type both the runtime and brief time and this is fantastic for me. If you want, you can also improve library, like in the Reactor-Router-DOM example, or you can also add whatever you want in your application if you need to guarantee your type system also at runtime.
6. Conclusion and Contact Information
I hope you enjoyed this talk. If you have any questions, feel free to reach out to me on Twitter or LinkedIn. You can also follow me on YouTube for more content. Thank you to everyone and bye-bye.
I think that's all. I hope you enjoy this talk, and if you have any question, I'm open and you are welcome. Here you can find the site of this talk.
Before leave this talk, I'm Luca Del Pupo, a Senior Software Developer at NearForm. I'm a Microsoft MVP, and a GitHub Ambassador. These are my contacts. Twitter and LinkedIn are open, so if you want to chat with me or drop a message, feel free to reach out and you are welcome. If you want to follow me on YouTube, this is my YouTube channel. If you want to read something in my WTO account, you can find something to read about technical stuff.
Okay, that's all. Thank you to everyone and bye-bye.
Comments