What We’ll Build
We’ll create a function that:- Fetches user data from an API
- Parses and validates the response
- Handles multiple error types (network, parsing, validation)
- Uses generator composition for clean control flow
- Provides type-safe error handling with pattern matching
Create Ok and Err Results
Let’s start with the basics — creating success and error Results:
Results use a discriminated union with
status: "ok" | "error" for type narrowing.Wrap Throwing Functions
Most JavaScript APIs throw exceptions. Wrap them with
Result.try to convert exceptions into type-safe Results:Define Tagged Errors
Create discriminated error types for exhaustive pattern matching:Now we can use custom error handlers in
Result.try:Compose with Result.gen
The real power of better-result comes from generator composition. Use
yield* to unwrap Results and automatically short-circuit on errors:user-profile.ts
yield* unwraps Ok values and short-circuits on Err. Use Result.await() to wrap Promise<Result> in async generators.Handle Errors with Pattern Matching
Now use the function and handle all possible errors:Alternatively, use
main.ts
Result.match() for inline pattern matching:Complete Example
Here’s the full working example:What You’ve Learned
You now know how to:- ✅ Create
OkandErrresults - ✅ Wrap throwing functions with
Result.tryandResult.tryPromise - ✅ Define custom error types with
TaggedError - ✅ Compose operations with
Result.genandyield* - ✅ Handle errors exhaustively with pattern matching
- ✅ Transform Results with
.map()and.andThen()