by nayajunimesh · 1y ago · 0 comments
import { object, string, number, validate } from "decode-kit";
// Example of untrusted data (e.g., from an API) const input: unknown = { id: 123, name: "Alice" };
// Validate the data (throws if validation fails) validate(input, object({ id: number(), name: string() }));
// `input` is now typed as { id: number; name: string } console.log(input.id, input.name);
When validation fails, decode-kit takes an equally thoughtful approach. Rather than being prescriptive about error formatting, it exposes a structured error system with an AST-like path that precisely indicates where validation failed. It does include a sensible default error message for debugging, but you can also traverse the error path to build whatever error handling approach fits your application - from simple logging to sophisticated user-facing messages.
The library also follows a fail-fast approach, immediately throwing when validation fails, which provides both better performance and clearer error messages by focusing on the first issue encountered.
I'd love to hear your thoughts and feedback on this approach.
would this mask any errors that would occur later in the validation?
My overall takeaway has mostly been to not optimize for the worst case by default. Keep fail-fast as baseline for boundaries and hot paths, and selectively enable “collect all” where it demonstrably saves human time.
We currently expose error as a tree structure so that it's easy to map an error to a value or build custom error messages (we only provide debug error message) and I haven't been able to come up with a satisfactory error API that accommodates multiple error paths, but you raise an excellent point. Thanks for pointing out.