Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

z.discriminatordUnion can't handle Unions #2121

Closed
WORMSS opened this issue Mar 1, 2023 · 4 comments
Closed

z.discriminatordUnion can't handle Unions #2121

WORMSS opened this issue Mar 1, 2023 · 4 comments
Labels
enhancement New feature or request

Comments

@WORMSS
Copy link

WORMSS commented Mar 1, 2023

z.discriminatordUnion() can't handle z.union()

const baseAttribute = const baseAttribute = z.object({
  name: nameSchema,
  code: z.string(),
});
const linkAttribute = baseAttribute.extend({
  type: z.literal('Link'),
  options: z.object({
    code: z.string(),
  }),
});
const otherAttribute = baseAttribute.extend({
  type: z.union([
    z.literal('Time'),
    z.literal('GeoJson'),
    z.literal('Boolean'),
  ]),
});

export const attributeSchema = z.discriminatedUnion('type', [linkAttribute, otherAttribute]);

I've just seen that you want to deprecate discriminatedUnion from #2109

But I was hoping this would be a super quick fix.

else if (type instanceof ZodUnion) {
  const accumulator = [];
  for ( const option of type.options ) {
    const types = getDiscriminator(option);
    if (types === null) {
      return null; // nested is of unknown type.
    }
    accumulator.push(...types);
  }
  return accumulator;
}
@JacobWeisenburger
Copy link
Contributor

considering discriminatedUnion is going to be deprecated. I'm not sure any more work should be done on it.

@colinhacks thoughts?

@JacobWeisenburger JacobWeisenburger added enhancement New feature or request closeable? This might be ready for closing labels Mar 4, 2023
@JacobWeisenburger
Copy link
Contributor

@WORMSS, I'm going to close this issue. Feel free to reopen if you have more to say.

@stdedos
Copy link

stdedos commented Apr 14, 2023

Is there a plan for that depreciation? It seems that #2106 was last updated last month.

Would there be a "quick fix" that would address this instead?

@dplantera
Copy link

Is there a plan for that depreciation? It seems that #2106 was last updated last month.

Would there be a "quick fix" that would address this instead?

You might wanna checkout #1845 (comment) where teunmooij introduced a dedicated fix with z.enum support which could handle your usecase. z.enum works fine for primitive homogeneous discriminator properties like in your example.

zod.discriminatedunion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

4 participants