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 level, making it a useful library to add to your repertoire.
A First Look at Runtime Checking
We're taking in a
num variable that we've typed as
This means that we can call
toString() with anything we want on the type level, including object types or
For now all of these would work, but we want to prevent this at the runtime level.
If we call
toString() with a string, we want it to throw an error and say that it expected a number but received a string:
If we pass in a number,
toString() should work as expected:
01-number.problem.ts, use Zod to update the tests to make them pass.
yarn e 01 to check your work.
Matt Pocock: 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.
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.
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.
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.
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.