colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
33.95k stars 1.19k forks source link

Allow nativeEnum() after coerce #3806

Open MickL opened 3 weeks ago

MickL commented 3 weeks ago

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);