Skip to content

Add option to use nativeEnum for Zod enums #3067

@Arnagos

Description

@Arnagos

Add option to use nativeEnum for Zod enums

Current behavior

Currently, generating enums to Zod schemas results in output like this:

export const Currency = zod.union([zod.literal(0), zod.literal(1)]);

export type Currency = zod.input<typeof Currency>;

This is useful for validation but not for development, where we would rather use the actual names defined in the source enum.

Generating the same object as a const results in this vastly more useful object for development:

export type Currency = (typeof Currency)[keyof typeof Currency];

export const Currency = {
  Chf: 0,
  Eur: 1
} as const;

Proposed behavior

It would be nice if we could have both at the same time.

Proposed solution

Luckily, Zod allows exactly that:

import { z as zod } from 'zod';

const CurrencyObject = {
  Chf: 0,
  Eur: 1
} as const;

export const CurrencySchema = zod.nativeEnum(CurrencyObject);

export const Currency = CurrencySchema.enum;

export type Currency = zod.input<typeof CurrencySchema>;

This way we can use the schema as CurrencySchema, and the named enum values as i.e. Currency.CHF

Metadata

Metadata

Assignees

No one assigned

    Labels

    zodZod related issue

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions