Zod === TypeScript, pero en tiempo de ejecución en tus aplicaciones de React

Rate this content
Bookmark
Slides

En esta charla, quiero mostrar cómo podemos usar Zod para garantizar el tipo en una aplicación de React en tiempo de ejecución. Las variables de entorno, las solicitudes HTTP, los formularios, etc., pueden crear problemas en nuestras aplicaciones, principalmente si contienen tipos inesperados. Usando Zod, podemos crear esquemas para garantizar los tipos esperados en nuestro editor en tiempo de ejecución. De esta manera, podemos reaccionar rápidamente cuando falta una variable de entorno o cuando alguien cambia el contrato de la API sin informarnos.
Una pequeña capa de validación en nuestras aplicaciones puede prevenir una mala experiencia de usuario y notificarnos de inmediato, para que podamos solucionar el problema lo antes posible y mitigar la visualización de datos incorrectos.

8 min
06 Jun, 2023

Video Summary and Transcription

La charla de hoy discute cómo Zod, una biblioteca de NPM, puede garantizar el sistema de tipos en tiempo de ejecución, proporcionando todos los beneficios de TypeScript. El método parse de Zod permite verificar si los objetos coinciden con el esquema, creando una capa de validación entre las aplicaciones y las API. Al combinar TypeScript con Zod, los desarrolladores pueden garantizar la seguridad de tipos tanto en tiempo de ejecución como en tiempo de compilación, evitando la ejecución de código con datos incorrectos y mejorando la experiencia del usuario.

Available in English

1. Garantizando el sistema de tipos en tiempo de ejecución con Zod

Short description:

Hoy hablo sobre cómo puedes garantizar tu sistema de tipos en tiempo de ejecución usando Zod. TypeScript no puede verificar los tipos en tiempo de ejecución, pero Zod, una biblioteca de NPM, te permite crear un esquema personalizado que permanece activo en tiempo de ejecución. Zod te ayuda a obtener todos los beneficios de TypeScript y garantiza tu sistema de tipos en tiempo de ejecución. Cada esquema expone un método llamado parse para verificar si el objeto cumple con el esquema esperado. Zod puede crear una capa de validación entre tu aplicación y la API, permitiéndote verificar si el resultado de la API cumple con lo esperado durante el desarrollo.

¡Hola! Soy Luca De Pupo y hoy hablo sobre cómo puedes garantizar tu sistema de tipos en tiempo de ejecución usando Zod. Así que, primero que nada, ¿quién soy yo? Soy Luca De Pupo, trabajo como ingeniero de software en Dreams, amante de JavaScript y TypeScript, y en mi tiempo libre intento mantener contenido en mi canal de YouTube y también escribir algunos artículos de blog. Me encanta correr, hacer senderismo y los animales.

Por cierto, quiero comenzar con una historia. Hoy, hace casi 10 años, nació TypeScript y probablemente todos los desarrolladores de JavaScript en el mundo estaban felices. Comenzamos a crear nuestras interfaces, nuestros tipos, y así sucesivamente. El mundo era perfecto, pero un día, un desarrollador de backend decidió cambiar una API y, desafortunadamente, cambió una propiedad de String a Number o de Number a String, y el resultado en nuestra aplicación fue algo como esto: NaN, una cadena, y así sucesivamente. Esto se debe a que TypeScript no puede verificar los tipos en tiempo de ejecución, ya que el código que se ejecuta en tu navegador es JavaScript. Pero, ¿cómo podemos prevenir este error? Nuestro superhéroe es Zod. Zod es una sencilla biblioteca de NPM que te permite crear un esquema personalizado. En este caso, el esquema es un objeto JavaScript, por lo que el esquema permanece activo también en tiempo de ejecución. Este esquema contiene una definición de tu tipo. En este caso, como puedes ver, el esquema del cliente es un objeto con cuatro propiedades: id de tipo Number, name, email y phone de tipo String. Luego, también puedes convertir este tipo, este esquema, en un tipo TypeScript, en este caso usando el método type. Es bastante sencillo, puedes usar el esquema y convertirlo a TypeScript. Esto te ayuda a obtener todos los beneficios de TypeScript, pero también garantiza tu sistema de tipos en tiempo de ejecución.

Por último, pero no menos importante, cada esquema expone un método llamado parse. Este método se utiliza para verificar si el objeto cumple con el esquema esperado. En este caso, si el objeto analizado por el método parse cumple con lo esperado, la variable customer es de tipo Customer y contiene el objeto. De lo contrario, parse genera un error. Este error es de tipo ZodError y contiene el problema y el error para entender qué está mal. ¿Cuáles son los beneficios de usar Zod en nuestra aplicación? Típicamente, cuando creas una aplicación, tienes tu aplicación de React y una API para obtener los datos. Usando Zod, puedes crear una capa de validación entre tu aplicación y la API. En tiempo de ejecución, puedes verificar si el resultado de la API cumple con lo esperado durante el desarrollo y, en este caso, solo puedes ejecutar el código si los tipos respetan el tipo esperado. De lo contrario, puedes mostrar un error al usuario y enviar una notificación a Datadog o tal vez a Sentry para solucionar el problema lo antes posible.

Ahora es el momento de ver una demostración sencilla para entender cómo podemos usar Zod y los beneficios de usarlo. La demostración es bastante simple. Hay una lista de pedidos y cada pedido tiene una propiedad diferente en este caso. Por ejemplo, si cambio mi backend, en este caso cambio el monto de número a cadena, y vuelvo a la aplicación y actualizo la página. Como puedes ver, en este caso Zod muestra un error y describe el problema.

2. Implementando Esquemas y Conclusiones

Short description:

En esta sección, vimos cómo identificar y solucionar problemas en el esquema. También exploramos cómo implementar esquemas utilizando .object y tipos de unión. El esquema se puede convertir en tipos y utilizar para validar los resultados de la API. TypeScript comprende el resultado del método parse y garantiza la seguridad de tipos. En conclusión, TypeScript, combinado con Zod, te permite garantizar tu sistema de tipos tanto en tiempo de ejecución como en tiempo de compilación. Esto ayuda a prevenir la ejecución de código con datos incorrectos y garantiza una mejor experiencia de usuario. También puedes recibir notificaciones y tomar medidas para solucionar cualquier problema rápidamente. ¡Gracias por unirte a esta charla!

Como puedes notar en la propiedad issue, puedes ver información sobre el problema. En este caso, en el path, el primer elemento de la lista contiene un objeto total que tiene una propiedad amount y esta propiedad amount es de tipo string, pero Zod espera un tipo number. Como puedes notar, puedes tener un error legible y tal vez solucionar el problema rápidamente si quieres.

Entonces, vuelvo a eso, retrocedo y soluciono el error y ahora es el momento de ver cómo podemos implementar este tipo de cosas. Por ejemplo, en este caso, creo un archivo más grande con todo el esquema que está compuesto usando .object y, por ejemplo, la moneda contiene un amount de tipo number y la moneda es un tipo de unión entre dólar y euro, por ejemplo, lo mismo ocurre con el pedido y así sucesivamente. Luego, si quieres, también puedes convertir el esquema en tipos. Bastante simple usando el método type y luego puedes usar el esquema para pasar el resultado de la API, por ejemplo.

En este caso, usando un fetch, podemos llamar al backend. Usando el método JSON, podemos pasar el resultado y luego usando el esquema del array de pedidos, podemos pasar el resultado de los datos y asegurarnos de que los datos sean del tipo del modelo de pedido y respeten nuestra firma del tipo, por ejemplo. Por ejemplo, si uso const res = "", puedes ver que el resultado es un array de pedidos y también TypeScript es capaz de entender que el resultado del parse es un array del modelo de pedido. Entonces, si vuelvo al navegador y actualizo nuevamente, como puedes notar, ahora todo está bien porque la respuesta es perfecta como se esperaba.

Ahora es el momento de llegar a la conclusión. Entonces, conclusión. TypeScript es increíble, pero sin Zod no puedes garantizar tu sistema de desarrollo también en tiempo de ejecución si quieres. Crear una capa de validación entre tu aplicación y el exterior te ayuda a prevenir la ejecución de código con datos incorrectos y tal vez a evitar que veas datos incorrectos o extraños en la interfaz de usuario. Y también puedes recibir una notificación... Puedes enviar una notificación a Datadog o a Sendit para solucionar el problema lo antes posible. Por último, pero no menos importante, usando Zod, puedes garantizar tu sistema de tipos tanto en tiempo de ejecución como en tiempo de compilación. Y esto es perfecto, supongo, también para ti. Bueno, eso es todo. Aquí puedes encontrar las diapositivas de la charla. Aquí puedes encontrar mis contactos, están abiertos. Si quieres chatear conmigo, eres bienvenido. Espero que hayas disfrutado esta charla y adiós. ♪♪♪

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