profile
viewpoint

Ask questionsDetailed errors for union schema

I'd like to have more information or even TS-like details for union errors (Add a flag to parse?):

My types:

export const T = z.union([
  A, B, C
])

So what I currently get from this is:

     Error: 1 validation issue(s)

  Issue #0: invalid_union at 
  Invalid input

What I'd like to get is something more similar to this:

'{ t: 1 }' is not assignable to parameter of type '{ a: number } | { b: number }'

Is this sensible|doable|easy|hard?

vriad/zod

Answer questions chrbala

It seems like this could be improved with a union resolver function as I proposed in https://github.com/vriad/zod/issues/100#issuecomment-667584554. As long as the input matches well enough (e.g. with a discriminator field) to be recognized as an element of the union in userland, the errors could be simplified to a single case instead of needing to resolve unionErrors within an invalid_union error type.

enum Number {
  FLOAT,
  INT,
}
const floatObj = z.object({
  kind: z.literal(Number.FLOAT),
  value: z.number(),
});
const intObj = z.object({
  kind: z.literal(Number.INT),
  value: z.number().refine(n => n % 1 === 0, "not_int"),
});

const resolver = (val: unknown) =>
  val && typeof val === 'object'
    ? val.kind === Number.FLOAT
      ? floatObj
      : intObj
    : null;

const union = z.union([floatObj, intObj], resolver);

const input = {
  kind: Number.INT,
  value: 5.5,
};

union.parse(input); // same result as intObj.parse(input);

So here, parsing input with into either the union or intObj schemas should result in:

Error: 1 validation issue(s)

  Issue #0: custom_error at value
  not_int
useful!

Related questions

No questions were found.
source:https://uonfu.com/
Github User Rank List