Be Specific with Allowed Types
We're validating forms again in this example.
This time Form
has a privacyLevel
that can be two types: either private or public:
const Form = z.object({ repoName: z.string(), privacyLevel: z.string(),});
If we were going to represent this in TypeScript, we would write:
Transcript
Matt Pocock: 0:00 Another day, another form. We are validating form inputs again, this time on a repoName, except that we've got this privacyLevel here. This privacyLevel, it's actually really only two types. It's going to be either private or public here.
0:15 If you were to represent this in TypeScript, you would say, "type PrivacyLevel = 'private' | 'public'." Of course, we could use a Boolean here, but we might need to add more privacy levels in the future. It's often safer to use a union type here or an enum.
0:31 Your challenge here then is we can see that the tests are not working. If we say "yarn e 07," then we can see that this is failing because you're not allowed to pass in something-not-allowed here. We need to restrict that somehow. Your challenge is to find an API in Zod that allows you to be more specific with the types of strings that you can pass in here.