The Decoder Class
At the heart of the library is theDecoder<T> interface. A decoder is an object that knows how to validate and transform unknown input data into a specific type T.
Every decoder provides three main methods for validation:
.decode() - Safe Validation
.decode() method never throws. It always returns a Result<T, Annotation> type that explicitly represents success or failure.
.verify() - Throwing Validation
.verify() method throws a DecodingError if validation fails. Use this when you want to fail fast and handle errors with try/catch.
.value() - Optional Validation
.value() method returns the decoded value on success, or undefined on failure. Use this when you don’t care about the error message.
The Result Type
TheResult<T, E> type is a discriminated union that represents either success or failure:
ok field:
DecodeResult<T> is an alias for Result<T, Annotation>.
Execution Model
Decoders follow a simple execution model:- Input Reception: The decoder receives untrusted data of type
unknown - Validation: The decoder checks if the data matches expected criteria
- Transformation: If valid, the decoder may transform the data (e.g., parsing strings to dates)
- Result Construction: The decoder returns either
ok(value)orerr(annotation)
Defining Custom Decoders
You can create custom decoders using thedefine() function:
blob: The untrusted input dataok: A function to accept the valueerr: A function to reject with an error message
Annotations
When a decoder fails, it produces anAnnotation object that captures:
- The value that failed validation
- An error message describing why it failed
- For complex types (objects/arrays), annotations for nested failures
Formatters
Decoders includes built-in formatters to display errors:.verify():
Key Takeaways
- Decoders validate untrusted data and provide type-safe outputs
- Use
.decode()for safe validation,.verify()for throwing validation - The
Resulttype explicitly represents success/failure states - Custom decoders are defined using the
define()function - Annotations capture detailed error information for helpful error messages
