✨ 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 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/
Top comments (4)
Small suggestion: you probably would help readers to consume the content in a more convenient way with code snippets instead of screenshots (the screenshots are hardly readable on mobile screens).
Thanks for your suggestion. I will improve my stories in the future.
Great series, and thanks for switching to code snippets, much more accessible now 👍 btw, you can use language-specific syntax highlighting in markdown here, just in case: by adding, for instance,
ts
right after the snippet-opening triple backtick, like “ts” or “html” (sorry, cannot put backticks directly here, dev transforms them right away 😅), check out one of the snippets from your latest post formatted this way:Thanks for sharing!