Create an Array of Custom Types
The correct way to solve this challenge is to create an object that references other objects. In this case
StarWarsPeopleResults will be a
z.object that contains
results we'll use
z.array and provide it with our
StarWarsPerson type. We don't have to repeat the
name: z.string() part!
Here's the code before:
Matt Pocock: 0:00 The correct way to represent this in Zod is with z.array. Now, what this does is we're basically creating an object which references another object, which is pretty cool. You can compose these together. I don't need to repeat all of this stuff inside my StarWarsPeopleResults.
0:16 What this means is the parsed data now looks like the interface that we declared before. We've got our results, which is name: string; and that returns properly. Again, we can console.log the parsed data. What's going to happen is that we get all of the names back, which is really, really nice.
0:35 You can use z.array in a few different ways, but this pretty basic method is what you need to know about z.array. It's really, really nice for declaring arrays of objects. Of course, if I wanted to, I could say z.object. I could declare this as z.string() if I wanted to. It takes any old object.
0:53 Of course, this is going to fail because we're actually getting back an array of objects there instead of an array of strings. Z.array allows you to parse anything to it that is something returned from a z. It's going to be...What does it take? Z.string?
1:10 I imagine it takes...Yeah, z.any, basically. You can even parse in z.any here, as well, which is a cool thing. That will allow any old thing to be parsed through. What we were getting here is we're grabbing StarWarsPerson and sticking it inside an array. That's working nicely.