Zod enums vs Native enums

From what I understood from the documentation of Zod, enum should be use as followed :
const FishEnum = z.enum(["Salmon", "Tuna", "Trout"]);
type FishEnum = z.infer<typeof FishEnum>;

// to use it
const someFish = FishEnum.parse("Salmon");
// to validate
const VALUES = ["Salmon", "Tuna", "Trout"] as const;
const FishEnum = z.enum(VALUES);
const FishEnum = z.enum(["Salmon", "Tuna", "Trout"]);
type FishEnum = z.infer<typeof FishEnum>;

// to use it
const someFish = FishEnum.parse("Salmon");
// to validate
const VALUES = ["Salmon", "Tuna", "Trout"] as const;
const FishEnum = z.enum(VALUES);
But it is also possible to use native enums :
export enum Countries {
Maroc = "Maroc",
Tunisie = "Tunisie",
Egypte = "Egypte",
}

// to use it
const someCountry = Countries.Maroc;
// to validate
const country = z.nativeEnum(Countries);
export enum Countries {
Maroc = "Maroc",
Tunisie = "Tunisie",
Egypte = "Egypte",
}

// to use it
const 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 ?
GitHub
TypeScript-first schema validation with static type inference
TypeScript-first schema validation with static type inference
GitHub
TypeScript-first schema validation with static type inference
TypeScript-first schema validation with static type inference
Solution:
This is how I use enums with Zod : ```javascript // Single source of truth: const fishes = ["Salmon", "Tuna", "Trout"] as const...
Jump to solution
3 Replies
KP
KP2y ago
Matt Pocock
YouTube
Enums considered harmful
TypeScript enums are not great. In almost all cases, I use an 'as const' with a sprinkling of type magic to express them. Become a TypeScript Wizard with Matt's TypeScript Course: https://www.totaltypescript.com/ Follow Matt on Twitter https://twitter.com/mattpocockuk
Solution
Benjamin
Benjamin2y ago
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];
Max
Max15mo ago
@Benjamin @Romain type: z.nativeEnum(YourPrismaEnum),
Want results from more Discord servers?
Add your server