You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Thanks for the great library, really finding it useful.
Is there a recommended way to define a union of two or more record schemas, that would successfully parse an object with a mix of key/values from each record? Here's a minimal example outlining my unsuccessful attempt:
import{z}from'zod';// Define the schemas for the individual recordsconstrecord1Schema=z.record(z.enum(['a','b']),z.union([z.number(),z.string()]));constrecord2Schema=z.record(z.enum(['c','d']),z.union([z.boolean(),z.string()]));// Define the merged schemaconstmergedSchema=z.union([record1Schema,record2Schema]);// Example usageconstexample1={a: 42,b: 'hello'};// Valid according to record1Schemaconstexample2={c: true,d: 'world'};// Valid according to record2Schemaconstexample3={a: 42,c: true};// Valid according to mergedSchemaconsole.log(record1Schema.safeParse(example1));// Successconsole.log(record2Schema.safeParse(example2));// Successconsole.log(mergedSchema.safeParse(example3));// Error
The last parse fails with invalid_union errors that includes invalid_enun_values errors like this:
I would expect it to work (and it does type check), but it seems like it expects it to conform to one of the record schemas only, and won't accept the other. Is there a better way to do this?
The text was updated successfully, but these errors were encountered:
Thanks for the great library, really finding it useful.
Is there a recommended way to define a union of two or more record schemas, that would successfully parse an object with a mix of key/values from each record? Here's a minimal example outlining my unsuccessful attempt:
The last parse fails with invalid_union errors that includes invalid_enun_values errors like this:
I would expect it to work (and it does type check), but it seems like it expects it to conform to one of the record schemas only, and won't accept the other. Is there a better way to do this?
The text was updated successfully, but these errors were encountered: