Discriminated Unions
Yeah, I was wondering about that, but can't figure out how to combine discriminated unions with other fields. Like in this case:
11 Replies
Something like that should work
And in general, this just sorta follows how you do it in TypeScript itself in the type-language:
Oh, I forgot the actual union:
That makes sense. But, seems like it could become quite crazy when there's more than one conditional field in a schema though 🤔
Which I guess it would become in Typescript as well, for that matter
yeah, discriminated unions should have a single discriminant. If you need to support structural discrimination, you can use
union
and just make sure the order of the schemas considers that we use the first match, so if two things share similar structures, make sure the schemas are in the right order.Actually, I suppose one solution would be to just separate it out, and then merge it together later in a transform?
Will require a bit of "stitching" at the end, but could be OK I would think.
Btw, is there a way to "aim" a schema to match a certain type? Or would that just be, in this case, to stick a generic on the
transform
function, which would check that the return matches whatever?Discriminated unions are really the only mechanism of "aiming" available.
I think extension is probably the most popular way to deal with these kinds of things, but there isn't anything wrong with your suggestion, too.
Yeah, this would be more of a workaround just to be able to deal with the large unwieldly pension applications we have in our solution. Multipart forms with lots of yes/no questions and details depending whatever. 🥴
Working my way towards trying to replace some horribly messy magical validation and form management code written by some "clever" consultants several years ago, hehe. Trying to replace it with
react-hook-form
and zod
, and I think it can work fairly OK, just need to create a framework of sorts around it allyeah, i've been blessed with applications that do not have big form-driven wizards in them, but I know that's a privilege! 😂
In theory I think it should work quite easily though. Just split each wizard-page into separate schemas, then merge them all together at the end before submit. "Easy-peasy" 🤞
so easy
Thanks for the help! Really appreciate it. 🙏
of course! definitely feel free to ask any questions here.
I'm a little better about checking here than in GitHub.