Result Type For Error Handling

Implement a Result type for explicit error handling without exceptions forcing callers to handle both cases.

TypescriptResilience

Code

snippet
export type Result<T,E=Error>= {ok:true;value:T}|{ok:false;error:E};export function ok<T>(value:T):Result<T,never>{return{ok:true,value};}export function err<E>(error:E):Result<never,E>{return{ok:false,error};}export function unwrap<T,E>(r:Result<T,E>):T{if(r.ok)return r.value;throw r.error;}export function map<T,U,E>(r:Result<T,E>,fn:(v:T)=>U):Result<U,E>{return r.ok?ok(fn(r.value)):r;}export function flatMap<T,U,E>(r:Result<T,E>,fn:(v:T)=>Result<U,E>):Result<U,E>{return r.ok?fn(r.value):r;}export async function fromPromise<T>(p:Promise<T>):Promise<Result<T,Error>>{try{return ok(await p);}catch(e){return err(e as Error);}}