Create an Object Schema
Change PersonResult to use
To start, we need to change
This tool allows us to construct objects with the keys and types we want.
Matt Pocock: 0:00 The solution here then is to change PersonResult here into a
z.object is a tool that you can use to construct objects. It's like an interface in TypeScript. If we wanted to do the same thing in TypeScript, we would say, "PersonResultType." We'd say, "name string," here. You can see again how Zod really, really copies what TypeScript does. It does it very effectively.
0:24 Here, what we're doing is we're basically using this to understand data, here. This data, now, it's typed as any in this position. parsedData, it's actually typed in the correct way. Zod understands the structure of the object here.
0:41 If we do the same thing we did last time and just console.log the data here, then we're going to get all our keys. We've got films, which is an array. Let's do
eye_color as well. If we add
eye_color, which is
z.string, then what this is going to do is it's going to add
eye_color onto the bottom here.
0:58 If we actually
parsedData here -- there we go -- you'll notice that it actually strips out all of the keys it doesn't understand too. What you end up with is a really pure, just the good stuff parsing thing.
1:16 What this means is you can get really, really cool. We can go even deeper on this, if you want to. Let's add another property into here. We could add even all of these properties. Zod wouldn't bat an eyelid. It would still work really, really well.
1:28 What it means is it does ignore keys that you parse that aren't specified on it. It would just reduce it to the amount of keys you have. That's the idea of z.object.