Create a Runtime and Type Safe Function with Generics and Zod
Here we have a makeZodSafeFunction
:
const makeZodSafeFunction = (
schema: unknown,
func: (arg: unknown) => unknown
) => {
return (arg: unknown) => {
const result = schema.parse(arg);
return func(result);
};
};
The goal is to be able to pass a schema and function
Transcript
0:00 In this exercise, we're going to be using Zod to make a Zod-safe function. We're going to be declaring a function inside here and, basically, passing in a function that we want to make runtime safe as well as type-safe. What this does is you can pass in a schema into the first argument.
0:17 We'll then return a function, addTwoNumbers. We get this addTwoNumbers argument. This is the object that addTwoNumbers or this args is expecting to receive. The idea is we run the parser before we run the function to make sure that what gets passed into the function is what we expect.
0:39 What this means is we're going to need some generics here because we need to infer this runtime argument and also the return type here. We're also going to need to think about the Zod types, which we got a little intro to before, to figure out exactly what this schema needs to look like and what that's going to infer.
1:00 Those are all the hints I'm going to give you. We should be able to pass anything in there. It shouldn't just be objects. We should be allowed to pass in a number, a tuple, or an array, whatever we want to do. You've got to think about the base level, what you want to represent that schema as, and see if you can figure out all of the pieces that you need to understand in order to build this.
1:21 The solution is elegant, I will tell you that. There's no casting needed here. There's nothing too fancy. It's just using some built-ins from Zod that I'm going to see if you can find your way around on your own. Good luck.