Zod — TypeScript-first schema declaration and validation library #4
✨ 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.
If this was a TypeScript interface, it might look like:
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!
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:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Substack: https://nhannguyendevjs.substack.com/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/