Create an Object Schema
Change PersonResult to use z.object
To start, we need to change PersonResult
into z.object()
.
This tool allows us to construct objects with the keys and types we want.
In this case, we want the name
which will be a string:
const PersonResult = z.object({
name: z.string(),
});
Note the similarities to how interfaces are created in TypeScript:
interface PersonResultType {
name: string;
}
Checking our Work
Inside of fetchStarWarsPersonName
, our parsedData
is now correctly typed and has a structure that Zod understands.
Recall that the response from the API call included lots of information we weren't interested in.
Now if we call console.log()
and pass in our parsedData
, we can see that Zod has stripped away all of the keys that we aren't interested in, and gives us only the name
.
Going Further
Any additional keys you add to the PersonResult
ZodObject
from the original API response will be included in the parsedData
.
Being able to specify exactly the data we want while being correctly typed is a really useful feature of Zod.
Transcript
Matt Pocock: The solution here then is to change PersonResult here into a z.object
. 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.
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.
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.
If we actually console.log
the 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.
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.
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.