Lesson

Work with Zod Literals and Enums Effectively

Use Zod for string schemas in TypeScript, including literals, enums, and native enums for room type validation

Access
Included
Transcript
Needs source

In this lesson we make string-based schemas more specific using Zod in TypeScript. We focus on defining allowed values for a room type, showing how to use literals and enums effectively.

Zod's z.literal method allows us to specify a single allowed value for a string schema. For example, if we want to define a room type as "premium" and make it backward-type-safe in TypeScript, we can use z.literal("premium") to ensure that only this value is valid.

z.enum lets us define a set of allowed string values. This is useful when we have multiple options for room types, like "standard", "premium" or "childrenFriendly".

z.enum creates a union of TypeScript-compatible string literals, making it easy to validate against multiple values. Zod enums can be used to extract or exclude specific values from the enum.

Finally, zod's z.nativeEnum a native enum creates an equivalent of TypeScript's native enum ("real enums", we could say).

We can validate against all these values just like we do with literals and enums.