


A tiny typescript library to get rid of try catches, and replace them with result types, inspired by Rust and Go error handling.

Under 650 bytes (minified and gzipped) and with no dependencies, TryResult only provides you with more elegant error handling and gives you functions that act as wrappers and catch errors in your own functions.
As with any package, install using your favorite package manager:
The base functionality of TryResult revolves around theResult type, which can either be anOk or anErr. You can create these results using theok anderr functions.
import{ok,err,Result,isOk,isErr}from"tryresult";// You can create a Result with a value or an errorconstsuccess=ok("Success!");// Result<string, Error>constfailure=err(newError("Something went wrong"));// Result<string, Error>// You can do typesafe checks of a Resultif(isOk(success)){console.log(success.value);// "Success!"}if(isErr(failure)){console.error(failure.error);// Error: Something went wrong}To do away with try-catch blocks around functions you can't control, you can use wrapping functions to automatically get aResult type.
import{tryFn,isErr}from"tryresult";// Capture throws from async or sync functionsconstresult=tryFn(()=>{returnJSON.parse('{"message": "Hello!"}');});constasyncResult=awaittryFn(async()=>{constresponse=awaitfetch('https://api.example.com/data');returnresponse.json();});// As shown above, the `Result` can be checkedif(isErr(result)){console.error("An error occurred:",result.error);// Guaranteed to be an Error object}else{console.log(result.value.message);// "Hello!"}Several utilities are provided to make working withResult types easier, and abstract common functionality.
import{match,okOr,okOrThrow,mapOk,mapErr}from"tryresult";// Match on the Result type to run different logic or return different values based on whether it's Ok or Errconstgreeting=match(result,{ok:(value)=>`Success:${value.message}`,err:(error)=>`Error:${error.message}`,});// Ignore errors and use a default value for when you don't care about the errorconstdata=okOr(result,{message:"Default message"});// If need be, you can throw an error if the Result is Errtry{constvalue=okOrThrow(result);console.log(value.message);}catch(error){console.error("Error was thrown:",error);}// Returned values can be transformed/mapped quicklyconstuppercased=mapOk(result,(value)=>value.toUpperCase());// The same is true for errors, and several mapping functions are providedconstbetterError=mapErr(result,(error)=>`Custom error:${error.message}`);More information can be found as part of function documentation, which can be viewed in your editor or in the source code.