Zod Tutorial (10 exercises)
solution

Use z.infer() to Extract a Type

Update the Logging Function

Using z.infer and passing it typeof StarWarsPeopleResults is the fix.

This passes in the schema from Zod, and returns a type that properly represents the data.

const logStarWarsPeopleResults = (
  data: z.infer<typeof StarWarsPeopleResults>,
) => {
  ...

Now when you hover over the line in VS Code, you can see that data is an object that contains the results.

Making updates to the StarWarsPerson schema will update the data inside the function right away.

This is a great way to use Zod for runtime validation and then getting our type validation from it as well!

An Alternative Solution

Alternatively, we could save the StarWarsPeopleResultsType in a type and export it from this file:

export type StarWarsPeopleResultsType = z.infer<typeof StarWarsPeopleResults>;

Then the logStarWarsPeopleResults function could be updated to provide the data type like so:

const logStarWarsPeopleResults = (data: StarWarsPeopleResultsType) => {
  data.results.map((person) => {
    console.log(person.name);
  });
};

This would also allow other files in the project to take advantage of the StarWarsPeopleResults type if needed.

Transcript

Matt Pocock: The way to do it is with z.infer. What you do with z.infer is you pass in the typeof StarWarsPeopleResults here. This is passing in the schema that you get from Zod. It returns a type that represents the data.

What you get here is data. If you hover over it, you get data, which is the object, with the results and name here. If we change this, if we had eye_color again, z.string, then what you end up with, that gets added to as well. This is a really brilliant way to use Zod to have your runtime validation and then get your type validation from it.

There's a slightly alternative way to do this as well, which is to just save this in a type. Then you can export it from this file. Other files in your repo can take advantage of it. As you can see, it's just a type with results and name here.