Zod - TypeScript-first schema declaration and validation library #4

Nhan Nguyen - Dec 8 '23 - - Dev Community

Image description

Create an Array of Custom Types

We are still using the Star Wars API like the previous story but this time we want all of the people it returns.

Image description

If this was a TypeScript interface, it might look like:

Image description

We will update StarWarsPeopleResults to use an object schema representing an array of StarWarsPerson objects.

We will update StarWarsPeopleResults to use an object schema representing an array of StarWarsPerson objects.

We create an object that references other objects. In this case, StarWarsPeopleResults will be a z.object that contains results.

For results, we will use z.array and provide it with our StarWarsPerson type. We don't have to repeat the name: z.string() part!

Image description

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


I hope you found it useful. Thanks for reading. 🙏
Let's get connected! You can find me on:

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player