Zod Tutorial (10 exercises)

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.

For 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:

And after:

If we console.log our parsedData, we get all of the names back as we'd expect.

Declaring arrays of objects like this is one of the most common uses for z.array(), especially when referencing types you already created.


Matt Pocock: 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.

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.

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.

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?

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.