Zod's Object Parsing: A Game Changer for TypeScript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up in this video we're gonna take a look at possibly the coolest feature there is about Zod now if you have no idea what Zod is it's a typescript library that goes beyond what typescript can even do it's really cool and let's get into the coolest feature some examples some important things to know when you're working with Zod and specifically using this feature to make your entire development process way easier and then we'll also take a look at a specific example where I use this feature in a production setting for my most recent open source project so first off let's dive into some examples okay hey so here we are this is inside of a node.js project and the reason it's JS is because typescript yes it does matter I mean we're using a typescript library after all but it's just kind of a pain to set up in notes so we're in an index.jsu okay so take a look at what we've got here it's a user that we've named John with an age of 30 and an email and you don't need to worry about the right side right here that is kind of what we're going to be working towards in this video and some examples that I'm going to use to explain all this okay so what Zod allows us to do and the feature that I meant in the intro is a feature of a zot that is called parsing and what parsing can do for us is super powerful so what we can do with zot is Define a schema and then according to that schema we can validate any object that we want let's go ahead and Define one of those schemas so I can show you exactly what I mean and there is a convention to name these schemas I normally call them user schema and I saw a lot of other people also implementing this exact same convention just so you know exactly what they are and when we import Z from Zod that is what we need to do for all this to work we get so much stuff right a lot of stuff that we can use but I want to highlight some parse stuff so with that schema that's going to allow us to parse and we Define the object that we want to parse so and here goes the ideal structure for the object that we want to ensure it has after we parse it so whatever the object looks like in this case the user object right here after parsing it should look like what we Define right now so let's say we want a name that is going to be a z dot string now we could also do something like a z dot literal and then here literally pass John right if the name should only be John in our case we're fine with any string that is the condition now we could also do number but then the parsing would fail because we are passing it a string but more on that later so the name we want to ensure it is always a string the age should always be a number and then the email that we want should always be a string and Zod also does something really cool we can also dot email so there is an email template already in here that validates this email for us so what this schema does is it always ensures after doing this following operation user schema dot parse and that is not a const we should say a cons validated user is equal to user schema and now we've got a bunch of options we can do and we want to take a look at the parts now there's also a safe parse I'm going to get to that in a second for now we're going to use the powers and what we want to pass um this user object right here so we can pass it in here okay so let's log that out console log validated user and see what happens I'm gonna move this over to the side for a second we won't need that let me clear the screen and then execute this file right here and of course we get an error and that might be because we need to pass commas now this is really a pain because JavaScript doesn't highlight that stuff for us while typescript does and but I think that might be the reason of the error so let's try restarting that and okay that was the error so we parse this object so we made sure it has this exact structure and we can see the name is John the H is 30 and the email is exactly what we have in the object now if we want to implement something that is not in the object we want to ensure the object always has the strip and for example the user also has a I don't know salary which is a z DOT number as well then you'll see what happens because this will throw an error if the object does not match the schema that we parse it with in this instance you can see salary Z DOT number fails so whenever using the powers that is what you should take away from this right now is you want to wrap that in a try catch because it throws right we want to catch that error and then we we can also say if if the error is an instance of and then from zot we get something really interesting called Z dot Zod error and then we can help the arrow accordingly so we can say error and you can see now it also has Type annotations so we can say error Dot message for example and then log that error Dot message so if if this parse fails we log the error message let's try that again let's create clear the screen and run this and I just noticed we also need to fix two things man it's such a pain that JavaScript doesn't highlight this so we also need to implement the comma there itself and obviously typescript would highlight that too we also want to put the validated user right there okay so debugging done and now we can see that it gets caught by the catch right so we get the code the expected the received now I'm not sure yet apparently the message didn't work I need to refine this I didn't prepare for this but that's how it did it in production it might be Zod issue as well I'm not sure but you can definitely catch the zot error and then just log the message and that works just fine however what you should take away is um that the pricing throws an error if you don't want that that is very much possible so we can also have the parts just like this and then do a save parse and what you can see with the safe Parts if we take a look at the validated user dot you can see there's data error and success so let's say this goes through right we remove the salary then this should go through and then let's log the validated users so you can see what it looks like let's run the script and we can see success is true and data and the parsed object great so now we know how parsing works but now you might ask Josh what is the coolest feature you were talking about and while it is the parse already take a look at this if we Implement something like oops no salary in here let's say one 1500 just save that now you're gonna see the really cool stuff so let's try this again let's do a normal parse because this will not throw an error remember the difference now is before we had the salary in the object that we want to ensure the structure of and now we have it on the object that we are parsing so there's a small but very important difference if we run this again you can see there is no error and interestingly enough what do we get back for the validated user is this object right here so only the stuff that is in the schema is present in the past object and everything else is removed and that is super cool if anyone finds a security vulnerability in your application and you're able to put something into your database this is the best method at least that I know of to ensure a certain kind of object structure with its parsing right here if somebody pollutes your object by doing I don't know what and they get stuff in there that you do not want then it's it's not going to get put into your database if you do it with Zod so this is super cool it gives you so many options you can have dot optional you can read up on all of that in the zoc and the Zod documentation that I'm going to link in the description but that is I think the coolest feature that I want to show you and also one very important thing that you want to know about when you're working with this is check this out I've prepared the little age array right here so in the salt documentation it says whenever we parse an object it is not referenced to by reference but in set by value is a deep copy so what that means is we get the age array and then we also want to define the H array in our parsing schema right here now I'm just going to copy the strike hatch block over here there's no point writing that ourselves right now and then I can already close this file uh we don't need that anymore so I've added the age array to the user I've already added the edge array I've also added the H array to the user schema so it's going to parse just fine and then let's take a look at the validated user and the normal user but we're not going to push anything yet I just want you to take a look at this see what happens yarn Dev because right now we're getting the exact same object twice let me drag this out a bit and scroll up so we can see and in both objects the properties that we get are exactly the same which makes sense considering we're parsing exactly the shape of the object however you remember what I said about the Deep copy right it is referenced by value and not by reference like arrays or normally are in JavaScript or objects in that matter as well remember all the simple types like strings and stuff are referenced by value but arrays are referenced by reference I guess that yeah I mean it's true it sounds weird so after saving that and then running yarndev see what happens it's very interesting so when I scroll up the validated user so whatever we parsed also and I'm gonna make this a bit larger for you has A4 at the end so we were able to mutate this array by pushing into it directly which is a mutating function but the original reference array was not affected at all so the original object did not get modified even though normally in job script these operations change the reference of the array and not the actual value so that's just one very important thing to know when you're working with this I think it's really convenient it makes working with salt even easier and that is the coolest feature about the about zot or possibly at least the coolest feature that I wanted to show you this object parsing hey thank you for watching I hope you enjoyed this one and if you did then chances are you probably also want to know how to write clean reusable react components and for that this video is going to be really helpful to you have a good one and bye bye
Info
Channel: Josh tried coding
Views: 6,182
Rating: undefined out of 5
Keywords: zod, typescript, zod typescript, zod react, react zod, react typescript, nextjs, nextjs zod, t3 stack, trpc, zod tutorial, zod js, zod parsing, zod documentation, tutorial, beginner, josh tried coding, joshtriedcoding
Id: RWWgUB9LmzQ
Channel Id: undefined
Length: 10min 19sec (619 seconds)
Published: Fri Feb 24 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.