A lightweight TypeScript library for assertion-based runtime data validation

https://news.ycombinator.com/rss Hits: 4
Summary

Lightweight, zero-dependency library for validating arbitrary runtime data in TypeScript. decode-kit provides assertion-based validation that refines your types in-place — no cloning, no transformations, and minimal runtime overhead. Installation npm install decode-kit Quick Start decode-kit validates your data and narrows its type in-place. Your original values remain unchanged - only their TypeScript types are refined. The validate function runs a runtime check and, on success, asserts the original variable's type. On failure, it throws a DecoderError . 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 ) ; Libraries like Zod, Valibot, Decoders, etc typically return a new (often transformed) value from .parse() . decode-kit instead asserts types directly - this provides several performance benefits as no time is spent copying arrays, strings or nested objects. This makes decode-kit ideal for performance-critical applications where memory efficiency and speed matter. Error handling decode-kit uses a fail-fast approach - validation stops and throws an error immediately when the first validation failure is encountered. This provides better performance and clearer error messages by focusing on the first issue found. The validate function throws a DecoderError if validation fails. This error object includes the path to the exact location of the validation failure (e.g., nested objects/arrays), the expected schema and ruleset that the value failed to match. Additionally, the error includes a pre-formatted human-readable error message. Example error message: Validation failed at user.age due to schema mismatch; expected schema: {"type...

First seen: 2025-08-25 14:14

Last seen: 2025-08-25 17:14