What is the ArkType equivalent of Zod's safeParse?

?
11 Replies
TizzySaurus
TizzySaurus2w ago
I'm not familiar with zod, but based on the docs entry it's just the default behaviour in ArkType?
If you don't want Zod to throw errors when validation fails, use .safeParse. This method returns an object containing either the successfully parsed data or a ZodError instance containing detailed information about the validation problems.
ArkType docs showing what I think is the same as zod's safeParse: https://arktype.io/docs/intro/your-first-type#validate
BozoWithTheBanjo
I was doing this to test arktype locally (so I might have done it wrong) with the moltar benchmark, and this is how I used safeParse in that context (also comparison with zod)
No description
Father Christmas
Father ChristmasOP2w ago
No, I mean zod literally has a schema.safeParse function that does not throw but instead returns something like an option - { success: true; data: T; } | { success: false; error: ZodError; }.
Father Christmas
Father ChristmasOP2w ago
I did not find this when searching for safeParse - I might have searched in the wrong input on Discord I am not familiar with such nuances. Also It did not provide the answer. I am mainly interested in the "non throwing" aspect of the safeParse method. I'd love to see the library have an equivalent instead of me having to either try catch or manually writing a function for that.
TizzySaurus
TizzySaurus2w ago
What are you after that what I sent doesn't do? Because "non throwing" is the default behavior, as outlined here: https://arktype.io/docs/intro/your-first-type#validate
Father Christmas
Father ChristmasOP2w ago
Oh I missed that part. In that case nothing much is a problem aside from the somewhat awkward ergonomics of x instanceof y instead of having a nice result value { success: true; data: T; } | { success: false; error: ZodError; }. This also helps in for example directly returning that whole result since it already looks like something you'd return with the "success" thing. I don't know how good returning this directly would be but again this is not a big deal.
TizzySaurus
TizzySaurus2w ago
I don't really see the difference... either way you need an if statement to handle it You're just checking if (result instanceof type.errors) instead of if (result.success === false)
IOM
IOM2w ago
Just wrap it in try catch in a function and if error return a value for the error then you'd have the equivlanet
ssalbdivad
ssalbdivad2w ago
In older versions there was a discriminated union like this, but the instanceof type.errors check seems better in terms of ergonomics and is definitely better in terms of performance (no need to create a new result object).
Father Christmas
Father ChristmasOP2w ago
Fair enough

Did you find this page helpful?