Zod Section 10 exercises
Problem

Runtime Type Checking with Zod

TypeScript is useful for checking the types of our variables at the type level.

However, we can't always be sure about what type of variables we'll get from external sources like API endpoints or form inputs.

Zod lets us work around this by checking types at the runtime level as well as the type l

Loading exercise

Transcript

Matt Pocock: 0:00 Zod is really, really useful at runtime when you want to make sure that a variable or anything, really, is of a certain type. Typescript does this on the type level, but Zod can do it on the runtime level and the type level.

0:15 Here, we've got a toString function where we're taking in this num variable which we've typed as unknown. That means we can call toString with anything we want on the type level. We call it with undefined. We can call it with an object.

0:30 What we want to do here is we want to actually prevent that at the runtime level. We want to say if you call it with a string, you want to say expected number and received string. We want it to throw an error.

0:42 We do want it to work when you pass it a number. This mimics a lot of situations that Zod is really, really helpful for. When you have a variable that you just don't know quite what type it is. You need to make sure it's a certain type.

0:56 A great example might be a form input or something coming from an external source, like an API endpoint or something. Your challenge is to somehow use Zod to make sure that these tests pass because if we run yarn e 01, then this is not going to parse unknown because this test is failing because it's not erroring in right way.