export enum Countries { Maroc = "Maroc", Tunisie = "Tunisie", Egypte = "Egypte",}// to use itconst someCountry = Countries.Maroc;// to validate const country = z.nativeEnum(Countries);
export enum Countries { Maroc = "Maroc", Tunisie = "Tunisie", Egypte = "Egypte",}// to use itconst someCountry = Countries.Maroc;// to validate const country = z.nativeEnum(Countries);
Using native enums seems more easy so, why would I use zod enums ? Have I missed something ?
TypeScript-first schema validation with static type inference
Solution
This is how I use enums with Zod :
// Single source of truth:const fishes = ["Salmon", "Tuna", "Trout"] as const// Use in a Zod Schema:const fishesSchema = z.enum(fishes)// Type to use in the code:// = "Salmon" | "Tuna" | "Trout"type FishType = (typeof fishes)[number];
// Single source of truth:const fishes = ["Salmon", "Tuna", "Trout"] as const// Use in a Zod Schema:const fishesSchema = z.enum(fishes)// Type to use in the code:// = "Salmon" | "Tuna" | "Trout"type FishType = (typeof fishes)[number];