DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

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

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:

Top comments (4)

Collapse
 
fyodorio profile image
Fyodor

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).

Collapse
 
nhannguyendevjs profile image
Nhan Nguyen

Thanks for your suggestion. I will improve my stories in the future.

Collapse
 
fyodorio profile image
Fyodor • Edited

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:

const Form = z.object({
  repoName: z.string(),
  privacyLevel: z.string(),
})

export const validateFormInput = (values: unknown) => {
  const parsedData = Form.parse(values);

  return parsedData;
}
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
nhannguyendevjs profile image
Nhan Nguyen

Thanks for sharing!