colinhacks / zod

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

Proposal: Include received value in union discriminator error messages #3783

Open Doryski opened 1 month ago

Doryski commented 1 month ago

Currently, when a union discriminator validation fails, the error message only includes the expected values but not the actual received value.

My proposition is to change: src/types.ts:

const discriminator = this.discriminator;

const discriminatorValue: string = ctx.data[discriminator];

const option = this.optionsMap.get(discriminatorValue);

if (!option) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union_discriminator,
        options: Array.from(this.optionsMap.keys()),
        path: [discriminator],
+        received: discriminatorValue,
   });
      return INVALID;
    }

and src/locales/en.ts:

case ZodIssueCode.invalid_union_discriminator:
-      message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
+      message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
      break;

If there are reasons for the current implementation, I'd appreciate any insights.