zod icon indicating copy to clipboard operation
zod copied to clipboard

Enum.extract() removes error messages

Open BrendanC23 opened this issue 1 year ago • 1 comments

If I declare an enum like

onst enumErrorMap = {
    errorMap: () => ({ invalid_type_error: "Error Message" }),
};

const TestEnum = z.enum(
    [
        "value1",
        "value2",
    ],
    enumErrorMap,
);

The error message works properly. However, if I do const TestEnumTwo = TestEnum.exclude(["value1"]);, the error map is lost. It looks like the code just creates a new enum and discards the RawCreateParams that were passed to the original enum.

https://github.com/colinhacks/zod/blob/a5a9d31018f9c27000461529c582c50ade2d3937/src/types.ts#L4065-L4076

BrendanC23 avatar Feb 09 '24 16:02 BrendanC23

I have confirmed this works as you have stated and I'm pretty sure this should be a bug.

const testEnum = z.enum( [ 'foo', 'bar' ], {
    errorMap: () => ( { message: 'Error Message' } ),
} )

const result1 = testEnum.safeParse( 'baz' )
!result1.success && console.log( result1.error.issues )
// [
//     {
//         received: "baz",
//         code: "invalid_enum_value",
//         options: [ "foo", "bar" ],
//         path: [],
//         message: "Error Message",
//     }
// ]

const result2 = testEnum.extract( [ 'foo' ] ).safeParse( 'baz' )
!result2.success && console.log( result2.error.issues )
// [
//     {
//         received: "baz",
//         code: "invalid_enum_value",
//         options: [ "foo" ],
//         path: [],
//         message: "Invalid enum value. Expected 'foo', received 'baz'",
//     }
// ]

JacobWeisenburger avatar Feb 09 '24 17:02 JacobWeisenburger

Fixed in Zod 3.23

colinhacks avatar Apr 21 '24 23:04 colinhacks