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
{{ message }}
Repository navigation
format() on a discriminated-union error should return a discriminated union
#1847
Let's say we have two forms on a page. Although they're unrelated, they're processed by the same API point, which uses a z.discriminatedUnion to differentiate them. There's currently no way to know, when there's a parsing error, which one is to blame.
constschema=z.discriminatedUnion("_formId",[z.object({_formId: z.literal(1),firstName: z.string(),}),z.object({_formId: z.literal(2),firstName: z.string(),}),]);constparsed=schema.safeParse(x);if(!parsed.success){constformatted=parsed.error.format();formatted.firstName?._errors;// <-- Is it coming from form 1 or 2?}
I believe the format() method in this case should return a discriminated union—with the discriminant being the original schema discriminant.
We'd be able to do that:
constparsed=schema.safeParse(x);if(!parsed.success){constformatted=parsed.error.format();if(formatted._formId===1){formatted.firstName?._errors;// <-- We know for sure it's coming from form 1.}if(formatted._formId===2){formatted.firstName?._errors;// <-- We know for sure it's coming from form 2.}}
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
Let's say we have two forms on a page. Although they're unrelated, they're processed by the same API point, which uses a
z.discriminatedUnionto differentiate them. There's currently no way to know, when there's a parsing error, which one is to blame.I believe the
format()method in this case should return a discriminated union—with the discriminant being the original schema discriminant.We'd be able to do that:
All reactions