Zod Section 10 exercises

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.

Loading solution


Matt Pocock: 0:00 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.

0:15 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.

0:37 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.