zod icon indicating copy to clipboard operation
zod copied to clipboard

Allow nativeEnum() after coerce

Open MickL opened this issue 1 year ago • 0 comments

Currently a string like "1" cant be casted to a number enum:

enum Animals {
   Dog, // 0
   Cat, // 1
}

const param = '1'; // From query params, always comes as a string

// This throws error, which is correct because param is a string:
const animal = z.nativeEnum(Animals).parse(param);

// This should work, but is not supported by zod, error: "Property nativeEnum does not exist on type ZodNumber"
const animal = z.coerce.number().nativeEnum(Animals).parse(param);

// This would be cool, too, error: "Property nativeEnum does not exist on type"
const animal = z.coerce.nativeEnum(Animals).parse(param);

Motivation

Query params always come as a string, e.g.

GET /animals/2

Will be "2" instead of 2 and therefor cant be casted to an enum with zod

Workaround

const animal = z.coerce.number().pipe(z.nativeEnum(Animal)).parse(param);

MickL avatar Oct 17 '24 14:10 MickL