DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

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

Image description

Verify Unknown APIs with an Object Schema

Zod is commonly used for verifying unknown APIs.

In the below example, we are fetching a person from the Star Wars API:

Image description

Note the call to PersonResult.parse() that takes in the data from the fetch request.

The PersonResult variable is created with z.unknown(). This tells us that our data is typed as any because we don't know what it is:

Image description

The issue of PersonResult is an unknown type that we need to fix:

Image description

We will change PersonResult into z.object(). This tool allows us to construct objects with the keys and types we want. In this case, we want the name which will be a string:

Image description

Inside of fetchStarWarsPersonName, our parsedData is now correctly typed and has a structure that Zod understands.

Recall that the response from the API call included lots of information we were not interested in.

Zod will strip away all of the keys that we aren't interested in, and gives us only the name.

Image description


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

Top comments (0)